广度优先搜索(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;
	    }
	}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东心十

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值