-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission Runtime - 3 ms (80.99%), Memory - 7.7 MB (9.…
…93%)
- Loading branch information
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>'1'</code>s (land) and <code>'0'</code>s (water), return <em>the number of islands</em>.</p> | ||
|
||
<p>An <strong>island</strong> 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.</p> | ||
|
||
<p> </p> | ||
<p><strong class="example">Example 1:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> grid = [ | ||
["1","1","1","1","0"], | ||
["1","1","0","1","0"], | ||
["1","1","0","0","0"], | ||
["0","0","0","0","0"] | ||
] | ||
<strong>Output:</strong> 1 | ||
</pre> | ||
|
||
<p><strong class="example">Example 2:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> grid = [ | ||
["1","1","0","0","0"], | ||
["1","1","0","0","0"], | ||
["0","0","1","0","0"], | ||
["0","0","0","1","1"] | ||
] | ||
<strong>Output:</strong> 3 | ||
</pre> | ||
|
||
<p> </p> | ||
<p><strong>Constraints:</strong></p> | ||
|
||
<ul> | ||
<li><code>m == grid.length</code></li> | ||
<li><code>n == grid[i].length</code></li> | ||
<li><code>1 <= m, n <= 300</code></li> | ||
<li><code>grid[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li> | ||
</ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
func numIslands(grid [][]byte) int { | ||
n := len(grid) | ||
m := len(grid[0]) | ||
vis := make([][]bool, n) | ||
for i := range vis { | ||
vis[i] = make([]bool, m) | ||
} | ||
ret := 0 | ||
for i := range grid { | ||
for j := range grid[i] { | ||
if vis[i][j] || grid[i][j] == '0' { | ||
continue | ||
} | ||
ret++ | ||
q := []int {i,j} | ||
for len(q) >= 2 { | ||
x := q[0] | ||
y := q[1] | ||
q = q[2:] | ||
if x < 0 || x >= n || y < 0 || y >= m || vis[x][y] || grid[x][y] == '0'{ | ||
continue | ||
} | ||
vis[x][y] = true | ||
q = append(q, x-1, y, x+1, y, x, y-1, x, y+1) | ||
} | ||
} | ||
} | ||
return ret | ||
} |