广度优先搜索(BFS)--leetcode200:求孤岛个数

200.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

这题大概的意思是,给出一个二维的地图,上面1表示岛屿,0表示海水,如果岛屿四面被水围住就是一个孤立的岛屿,根据地图求出孤立的岛屿个数。相对于上一篇文章提到的八皇后问题本题是一个广度有限搜索的问题。与深度有限不同的是,广度优先搜索不需要用递归,相对简单很多,思路就是只要拿到一块岛屿,把所有的岛屿都搜索出来,直到没有相邻的岛屿被搜索,那就认为已经搜索出了一片岛屿,代码如下:

	class Solution {
		class Grid{
			int x;
			int y;
			public Grid(int x, int y) {
				this.x = x;
				this.y = y;
			}
		}
		
		private char[][] grid=null;
		private boolean[][] record = null;
		private int rows = 0;
		private int cols = 0;
		LinkedList<Grid> queue = new LinkedList<Grid>();
		private int[][] directions = {{0,-1},{-1,0},{0,1},{1,0}};//左、上、右、下
		private int count = 0;
		
		private void bfs() {
			while(queue.size()>0) {
				Grid oldGrid = queue.pop();
				for(int[] direction:directions) {
					int xx = oldGrid.x+direction[0];
					int yy = oldGrid.y+direction[1];
					if(xx>=0&&xx<rows&&yy>=0&&yy<cols&&!record[xx][yy]&&grid[xx][yy]=='1') {
						record[xx][yy] = true;
						queue.add(new Grid(xx, yy));
					}
				}
			}
			count++;
		}
		
	    public int numIslands(char[][] grid) {
            if(grid.length<=0) return 0;
	    	this.grid= grid;
	    	rows = grid.length;
	    	cols = grid[0].length;
	    	record = new boolean[rows][cols];
	        for(int i=0; i<rows; i++) {
	        	for(int j=0; j<cols; j++) {
	        		if(grid[i][j]=='1'&&!record[i][j]) {//当前块是岛屿,并且没被搜索过
	        			Grid g= new Grid(i, j);
	        			record[i][j] = true;
	        			queue.add(g);
	        			bfs();
	        		}
	        	}
	        }
	    	return this.count;
	    }
	}

广度优先搜索(BFS)--leetcode200:求孤岛个数_第1张图片
上图第一次没有提交成功的原因是没有做判空 (if(grid.length<=0) return 0;),联系到笔者最近做很多的笔试题的情况,如果第一个案例刚好就是因为没有做判空而通不过,后面的案例全部都通不过。那样就很可惜,这里不讲代码强壮性那么大的概念,只要求做一下判空,很多笔试题能通过百分之八九十都是因为判空没做好。

你可能感兴趣的:(java,leetcode刷题)