刷题200. Number of Islands

一、题目说明

题目200. Number of Islands,在一个0(代表水)和1(代表陆地)组成的2d地图中,计数“岛屿”的数量。

二、我的解答

本题目计算图的最大连通分量,可以用图的深度优先遍历,也可用图的广度优先遍历。

深度优先遍历算法,代码如下:

class Solution {
	public:
	//图的深度优先遍历
	void dfs(vector>& grid,int i,int j,int row,int col){
		if(grid[i][j]=='1'){
			grid[i][j] = '.';
			//向左
			if(j>0){
				dfs(grid,i,j-1,row,col);
			}
			//向右 
			if(j0){
				dfs(grid,i-1,j,row,col);
			}
			
		}
		return;
	} 
	int numIslands(vector>& grid) {
		if(grid.size()<1 || grid[0].size()<1) return 0;
		
		count = 0;
		int row,col;
		row = grid.size();
		col = grid[0].size();

		for(int i=0;i

性能:

Runtime: 12 ms, faster than 92.90% of C++ online submissions for Number of Islands.
Memory Usage: 10.8 MB, less than 85.39% of C++ online submissions for Number of Islands.

三、优化措施

用广度优先遍历算法,需要一个栈,或者队列。

class Solution {
	public:
	//图的广度优先遍历
	int numIslands(vector>& grid) {
		if(grid.size()<1 || grid[0].size()<1) return 0;
		
		count = 0;
		int row,col;
		row = grid.size();
		col = grid[0].size();

		for(int i=0;i(i,j));
					while(! q.empty()){
						pair p = q.front();
						q.pop();
						int iTmp = p.first;
						int jTmp = p.second;
						//左 
						if(jTmp>0 && grid[iTmp][jTmp-1] == '1'){
							grid[iTmp][jTmp-1] = '.';
							q.push(pair(iTmp,jTmp-1));
						}
						//右
						if(jTmp+1(iTmp,jTmp+1));
						}
						//上 
						if(iTmp>0 && grid[iTmp-1][jTmp] == '1'){
							grid[iTmp-1][jTmp] = '.';
							q.push(pair(iTmp-1,jTmp));
						}
						//下 
						if(iTmp+1(iTmp+1,jTmp));
						}
					}
				}
			}
		}
		
		return count;
	}
	private:
		int count;
		queue> q;
};

性能如下:

Runtime: 16 ms, faster than 63.82% of C++ online submissions for Number of Islands.
Memory Usage: 11 MB, less than 47.19% of C++ online submissions for Number of Islands.

你可能感兴趣的:(刷题200. Number of Islands)