Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created May 25, 2020 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shixiaoyu/1882de7f135cc86ce1677137efb57c31 to your computer and use it in GitHub Desktop.
Save shixiaoyu/1882de7f135cc86ce1677137efb57c31 to your computer and use it in GitHub Desktop.
private final int[] xDirection = {1, 0, -1, 0};
private final int[] yDirection = {0, -1, 0, 1 };
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int islandCount = 0;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '0' || visited[i][j]) {
continue;
}
explore(i, j, m, n, grid, visited);
islandCount++;
}
}
return islandCount;
}
private void explore(int x, int y, int row, int col, char[][] grid, boolean[][] visited) {
if (!this.shouldExplore(x, y, row, col, grid, visited)) return;
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
explore(x + this.xDirection[i], y + this.yDirection[i], row, col, grid, visited);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment