Problem: 200. 岛屿数量
文章目录
- 思路
- 复杂度
- Code
思路
复杂度
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)
Code
class Solution {
int n, m;
public int numIslands(char[][] grid)
{
n = grid.length;
if (n == 0)
return 0;
m = grid[0].length;
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (grid[i][j] == '1')
{
dfs(grid, i, j);
ans++;
}
return ans;
}
private void dfs(char[][] g, int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '0')
return;
g[x][y] = '0';
int[] dx = { 0, 1, 0, -1 };
int[] dy = { 1, 0, -1, 0 };
for (int i = 0; i < 4; i++)
dfs(g, x + dx[i], y + dy[i]);
}
}