[LeetCode ] Number of Islands

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GYH0730/article/details/84338381

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

题意:找出图中岛的个数。

思路:广搜

Java代码:

class node
{
	int x,y;
	node(int x,int y) {
		this.x = x;
		this.y = y;
	}
}
public class Solution {
	 public void BFS(int sx,int sy,char[][] grid)
	 {
		 int[][] to = new int[][]{ {1,0},{-1,0},{0,1},{0,-1} };
		 node[] queue = new node[20005];
		 int head,tail;
		 head = tail = 0;
		 grid[sx][sy] = '-';
		 queue[tail++] = new node(sx,sy);
		 while(head < tail) {
			 node now = queue[head++];
			 int tx,ty;
			 for(int i = 0; i < 4; i++) {
				 tx = now.x + to[i][0];
				 ty = now.y + to[i][1];
				 if( !(tx >= 0 && ty >= 0 && tx < grid.length && ty < grid[0].length) ) continue;
				 if(grid[tx][ty] != '1') continue;
				 grid[tx][ty] = '-';
				 queue[tail++] = new node(tx,ty);
			 }
		 }
	 }
	 public int numIslands(char[][] grid) {
		 int num = 0;
		 for(int i = 0; i < grid.length; i++) {
			 for(int j = 0; j < grid[i].length; j++) {
				 if(grid[i][j] == '1') {
					 num++;
					 BFS(i,j,grid);
				 }
			 }
		 }
		 return num;
	 }
}

猜你喜欢

转载自blog.csdn.net/GYH0730/article/details/84338381