1. 程式人生 > >[LeetCode ] Number of Islands

[LeetCode ] Number of Islands

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;
	 }
}