200 Number of Islands
200. Number of Islands
1. Question
11110
11010
11000
0000011000
11000
00100
000112. Implementation
3. Time & Space Complexity
Last updated
11110
11010
11000
0000011000
11000
00100
00011Last updated
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int m = grid.length, n = grid[0].length;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++count;
searchByBFS(grid, i, j, m, n, directions);
}
}
}
return count;
}
public void searchByBFS(char[][] grid, int row, int col, int m, int n, int[][] directions) {
grid[row][col] = '0';
Queue<Integer> queue = new LinkedList<>();
queue.add(row * n + col);
while (!queue.isEmpty()) {
int curPoint = queue.remove();
int curRow = curPoint / n;
int curCol = curPoint % n;
for (int[] direction : directions) {
int nextRow = curRow + direction[0];
int nextCol = curCol + direction[1];
if (isValid(grid, nextRow, nextCol)) {
grid[nextRow][nextCol] = '0';
queue.add(nextRow * n + nextCol);
}
}
}
}
public boolean isValid(char[][] grid, int row, int col) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == '1';
}
}class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int count = 0;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++count;
searchIslandByDFS(i, j, grid, directions);
}
}
}
return count;
}
public void searchIslandByDFS(int row, int col, char[][] grid, int[][] directions) {
grid[row][col] = '0';
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (isValid(nextRow, nextCol, grid)) {
searchIslandByDFS(nextRow, nextCol, grid, directions);
}
}
}
public boolean isValid(int row, int col, char[][] grid) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == '1';
}
}