Number of Islands(leetcode200))
题目给的一个二维数组只含有0和1两个字符。其中1代表陆地0代表水域。横向和纵向的陆地连接成岛屿被水域分隔开。问给出的地图中有多少岛屿示例一输入11110110101100000000输出1示例二输入11000110000010000011输出2思路flood fill方法代码如下package com.haobi; public class NumberofIslands { private static int m, n; // 搜索顺序 private static int d[][] {{-1,0},{0,1},{1,0},{0,-1}}; private static boolean visited[][]; private static boolean inArea(int x, int y) { return x0 xm y0 yn; } public static void main(String[] args) { //示例1 char[][] c1 {{1,1,1,1,0}, {1,1,0,1,0}, {1,1,0,0,0}, {0,0,0,0,0}}; //示例2 char[][] c2 {{1,1,0,0,0}, {1,1,0,0,0}, {0,0,1,0,0}, {0,0,0,1,1}}; System.out.println(numIslands(c2)); } public static int numIslands(char[][] grid) { m grid.length; n grid[0].length; //初始化 visited new boolean[m][n]; int res 0; for(int i0;im;i) { for(int j0;jn;j) { if(grid[i][j] 1 !visited[i][j]) { res; dfs(grid, i, j); } } } return res; } /** * 递归算法 * 从grid[x][y]的位置开始进行floodfill * 保证x,y是合法的且grid[x][y]是没有被访问过的陆地 * param grid * param x * param y */ private static void dfs(char[][]grid, int x, int y) { visited[x][y] true; //搜索四个方向 for(int i0;i4;i) { int newx x d[i][0]; int newy y d[i][1]; if(inArea(newx, newy) !visited[newx][newy] grid[newx][newy] 1) { dfs(grid, newx, newy); } } return; } }程序输出结果如下3