From 5a95329fa7a60cc4bbcff0444bb8c1b055638419 Mon Sep 17 00:00:00 2001 From: Jayant Sogikar Date: Thu, 1 Oct 2020 00:42:16 +0530 Subject: [PATCH] Added a medium question in swift folder Added a medium question called Number Of Islands in swift folder --- leetcode/Swift/No200.number-of-islands.swift | 47 ++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 leetcode/Swift/No200.number-of-islands.swift diff --git a/leetcode/Swift/No200.number-of-islands.swift b/leetcode/Swift/No200.number-of-islands.swift new file mode 100644 index 0000000..aada8a8 --- /dev/null +++ b/leetcode/Swift/No200.number-of-islands.swift @@ -0,0 +1,47 @@ +/* +https://leetcode.com/problems/number-of-islands/ +Difficulty: + Medium +Desc: +Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. +Example: + Input: grid = [ + ["1","1","1","1","0"], + ["1","1","0","1","0"], + ["1","1","0","0","0"], + ["0","0","0","0","0"] + ] + Output: 1 + + Exaplanation: Whenever you encounter a land, sink all the possible lands you encounter around you and increment the counter by 1 +*/ +import UIKit +class Medium_099_Number_Of_Islands{ +func numIslands(_ grid: [[Character]]) -> Int { + guard grid.count > 0 else { return 0 } + guard grid[0].count > 0 else { return 0 } + var grid = grid + var islandCounter = 0 + for i in 0..= 0 && j >= 0 && i < grid.count && j < grid[i].count && grid[i][j] == "1" { + grid[i][j] = "0" + LandSink(&grid, i+1, j) + LandSink(&grid, i-1, j) + LandSink(&grid, i, j+1) + LandSink(&grid, i, j-1) + } + else{ + return + } +} +}