DFS solution.
public class Solution {
public int numIslands(char[][] grid) {
int row = grid.length;
if (row == 0) return 0;
int col = grid[0].length;
int count = 0;
for (int i=0; i<row; i++)
for (int j=0; j<col; j++) {
// must be an island when we meet a 1
if (grid[i][j] == '1') {
count++;
dfs(i, j, grid);
}
}
return count;
}
public static void dfs(int i, int j, char[][] grid) {
if (i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j] == '0') return;
// set current cell as water (visited)
grid[i][j] = '0';
// expand the island untill reach edges
dfs(i-1, j, grid);
dfs(i, j-1, grid);
dfs(i+1, j, grid);
dfs(i, j+1, grid);
}
}
BFS solution.
public class Solution {
public int numIslands(char[][] grid) {
if (grid.length == 0) {
return 0;
}
int num = 0;
int row = grid.length;
int col = grid[0].length;
// for a node in the grid, if it is an island, then start from this node,
// expand the island using BFS and mark all visited island as water
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
if (grid[i][j] == '1') {
num++;
bfs(i, j, grid);
}
}
}
return num;
}
private static class Node {
private int x;
private int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
private static void bfs(int i, int j, char[][] grid) {
// set island as water
grid[i][j] = '0';
int row = grid.length;
int col = grid[0].length;
Node node = new Node(i, j);
Queue<Node> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()) {
Node curr = queue.poll();
int x = curr.x;
int y = curr.y;
// check top
if (x-1>=0 && grid[x-1][y] == '1') {
grid[x-1][y] = '0';
Node newNode = new Node(x-1, y);
queue.offer(newNode);
}
// check bottom
if (x+1<row && grid[x+1][y] == '1') {
grid[x+1][y] = '0';
Node newNode = new Node(x+1, y);
queue.offer(newNode);
}
// check left
if (y-1>=0 && grid[x][y-1] == '1') {
grid[x][y-1] = '0';
Node newNode = new Node(x, y-1);
queue.offer(newNode);
}
// check right
if (y+1<col && grid[x][y+1] == '1') {
grid[x][y+1] = '0';
Node newNode = new Node(x, y+1);
queue.offer(newNode);
}
}
}
}