[LeetCode]Number of Islands
public class Solution { public int numIslands(char[][] grid) { int row = grid.length; if (row == 0) { return 0; } int col = grid[0].length; int[][] record = new int[row][col]; int result = 1; for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (grid[r][c] == '1' && record[r][c] == 0) { helper(grid, record, r, c, result++); } } } return result - 1; } public void helper(char[][] grid, int[][] record, int r, int c, int tmp) { record[r][c] = tmp; if (r > 0 && grid[r - 1][c] == '1' && record[r - 1][c] == 0) { helper(grid, record, r - 1, c, tmp); } if (r + 1 < grid.length && grid[r + 1][c] == '1' && record[r + 1][c] == 0) { helper(grid, record, r + 1, c, tmp); } if (c > 0 && grid[r][c - 1] == '1' && record[r][c - 1] == 0) { helper(grid, record, r, c - 1, tmp); } if (c + 1 < grid[0].length && grid[r][c + 1] == '1' && record[r][c + 1] == 0) { helper(grid, record, r, c + 1, tmp); } } }
Union Find
public class Solution { private int[] array; private int row, col; public int numIslands(char[][] grid) { int row = grid.length; if (row == 0) { return 0; } int col = grid[0].length; this.row = row; this.col = col; array = new int[row * col]; Arrays.fill(array, -1); for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { int x = r * col + c; if (grid[r][c] == '1') { if (array[x] == -1) { array[x] = x; } if (r > 0 && grid[r - 1][c] == '1') { set(r - 1, c, r, c); } if (r + 1 < row && grid[r + 1][c] == '1') { set(r + 1, c, r, c); } if (c > 0 && grid[r][c - 1] == '1') { set(r, c - 1, r, c); } if (c + 1 < col && grid[r][c + 1] == '1') { set(r, c + 1, r, c); } } } } int result = 0; for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { int x = r * col + c; if (array[x] == x) { result ++; } } } return result; } private int find(int x) { int y = array[x]; if (y != -1 && x != y) { return find(y); } return y; } private void set(int r1, int c1, int r2, int c2) { int tmp1 = find(r1 * col + c1); int tmp2 = find(r2 * col + c2); if (tmp1 == -1) { array[r1 * col + c1] = tmp2; } else { array[tmp1] = tmp2; } } }