dfs查找并集
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
public class LandSolution { private static boolean visited[][]; public static void main(String[] args) { char[][] grid_1 = { {'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'} }; char[][] grid_2 = { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'} }; System.out.println(numIslands(grid_1)); System.out.println(numIslands(grid_2)); } public static int numIslands(char[][] grid) { int x = grid.length; int y = grid[0].length; visited = new boolean[x][y]; int count = 0; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (!visited[i][j] && grid[i][j] == '1') { count++; dfs(grid, i, j); } } } return count; } private static final int step[][] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; public static void dfs(char[][] grid, int i, int j) { visited[i][j] = true; for (int k = 0; k < step.length; k++) { int x = i + step[k][0]; int y = j + step[k][1]; if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == '1' && !visited[x][y]) { dfs(grid, x, y); } } } }

浙公网安备 33010602011771号