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.
给定一个二维栅格地图,其中“ 1”(土地)和“ 0”(水),计算岛屿的数量。 一个岛屿被水包围,是通过水平或垂直连接相邻的陆地而形成的。 您可以假定网格的所有四个边缘都被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
方法:采用深度优先遍历,把访问过的改为‘0’,继续遍历。
import java.util.Scanner;
class Solution{
public static int numIsLand(char[][] grid)
{
int count = 0;
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[i].length;j++)
{
if(grid[i][j]=='1')
{
count+=1;
callBFS (grid,i,j);
}
}
}
return count;
}
public static void callBFS(char[][] grid,int i,int j)
{
if(i<0||i>=grid.length||j<0||j>=grid[i].length||grid[i][j] == '0')
return;
grid[i][j] ='0';
callBFS (grid,i+1,j);//up
callBFS (grid,i-1,j);//down
callBFS (grid,i,j-1);//left
callBFS (grid,i,j+1);//rigth
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m=in.nextInt();
int n=in.nextInt();
char[][]arr=new char[m][n];
for (int i = 0; i <m ; i++) {
String s=in.next();
for (int j = 0; j <n ; j++) {
arr[i][j]=s.charAt(j);
}
}
System.out.println(numIsLand(arr));
in.close();
}
}