Skip to content

Commit

Permalink
Sync LeetCode submission Runtime - 3 ms (80.99%), Memory - 7.7 MB (9.…
Browse files Browse the repository at this point in the history
…93%)
  • Loading branch information
hucancode committed Apr 19, 2024
1 parent 6df3dfa commit 347780b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
38 changes: 38 additions & 0 deletions leetcode/0200-number-of-islands/README.md
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>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</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>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [
[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]
]
<strong>Output:</strong> 1
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
[&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],
[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;]
]
<strong>Output:</strong> 3
</pre>

<p>&nbsp;</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 &lt;= m, n &lt;= 300</code></li>
<li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
</ul>
29 changes: 29 additions & 0 deletions leetcode/0200-number-of-islands/solution.go
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
}

0 comments on commit 347780b

Please sign in to comment.