200. Number of Islands
Description
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.
Constraints
Approach
Links
YouTube
Examples
Input: grid = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
Output: 1
Solutions
/**
* Time complexity : O(M*N), Where M is row size and N is column size
* Space complexity : O(1)
*/
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int row = grid.length;
int col = grid[0].length;
int count = 0;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(grid[i][j] == '1') {
count++;
merge(grid, row, col, i, j);
}
}
}
return count;
}
private void merge(char[][] grid, int row, int col, int i, int j) {
if(i < 0 || i >= row || j < 0 || j >= col) return;
if(grid[i][j] != '1') return;
grid[i][j] = 'X';
merge(grid, row, col, i-1, j);
merge(grid, row, col, i+1, j);
merge(grid, row, col, i, j-1);
merge(grid, row, col, i, j+1);
}
}
Follow up
Last updated
Was this helpful?