200. Number of Islands (Medium)
https://leetcode.com/problems/number-of-islands/
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
Solutions
class Solution {
// Apply union find technique to traverse all the islands. Turn the visited land from 1 to 2 during
// traversing the grid. After search up all the directly or indirectly linked lands, the island count
// increase by 1.
public int numIslands(char[][] grid) {
int ans = 0;
if (grid == null || grid.length == 0) {
return ans;
}
int rLen = grid.length;
int cLen = grid[0].length;
for (int i = 0; i < rLen; i++) {
for (int j = 0; j < cLen; j++) {
if (grid[i][j] == '1') {
infect(grid, i, j);
ans++;
}
}
}
return ans;
}
private void infect(char[][] grid, int x, int y) {
int rLen = grid.length;
int cLen = grid[0].length;
// check out if overstep the boundary
if (x < 0 || y < 0 || x >= rLen || y >= cLen) {
return;
}
if (grid[x][y] != '1') {
return;
}
grid[x][y] = '2';
int[] R = new int[]{-1, 0, 0, 1};
int[] C = new int[]{0, -1, 1, 0};
for (int k = 0; k < 4; k++) {
int row = x + R[k];
int col = y + C[k];
infect(grid, row, col);
}
}
}