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 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
题目链接:https://leetcode.com/problems/number-of-islands/
题目分析:DFS
2ms,时间击败86.6%
class Solution {
public int[] dx = {1, 0, -1, 0};
public int[] dy = {0, 1, 0 ,-1};
public void DFS(int x, int y, int n, int m, char[][] grid, boolean[][] vis) {
vis[x][y] = true;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && yy >= 0 && xx < n && yy < m && grid[xx][yy] == '1' && !vis[xx][yy]) {
DFS(xx, yy, n, m, grid, vis);
}
}
}
public int numIslands(char[][] grid) {
int n = grid.length;
if (n == 0) {
return 0;
}
int m = grid[0].length;
int ans = 0;
boolean[][] vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1' && !vis[i][j]) {
DFS(i, j, n, m, grid, vis);
ans++;
}
}
}
return ans;
}
}