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
这道题是求矩阵中连续区域(上,下,左,右为联通)的个数。
思路:从左上到右下loop每个cell,如果该cell是‘1’,想方法把它所在的连续区域找到并标记,同一连续区域里的其他cell在后面的loop中应该被跳过。
避免重复,记录cell有没有被visited,可以用哈希表/boolean matrix;当cell值为‘1’并且没有被visited过,用BFS/DFS找到它所属的连续区域里的所有值为‘1’的cell,把它们标记为visited。
计划:
1. bool类型的matrix来记录每个cell是不是被visited
2. DFS实现(用recursion 或者stack)
代码:
DFS with recursion
1 class Solution { 2 public: 3 int numIslands(vector<vector<char>>& grid) { 4 if(grid.size()==0||grid[0].size()==0){ 5 return 0; 6 } 7 8 vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size())); 9 int count = 0; 10 for(int i=0;i<grid.size();i++){ 11 for(int j=0;j<grid[0].size();j++){ 12 if(grid[i][j]=='1'&&!visited[i][j]){ 13 count++; 14 dfs(grid,i,j,visited); 15 } 16 } 17 } 18 return count; 19 } 20 private: 21 void dfs(vector<vector<char>>&grid, int i, int j, vector<vector<bool>>& visited){ 22 visited[i][j]=true; 23 int dirs[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; 24 for(auto dir: dirs){ 25 int x = dir[0]+i; 26 int y = dir[1]+j; 27 if(x>=0&&y>=0&&x<grid.size()&&y<grid[0].size()&&grid[x][y]=='1'&&!visited[x][y]){ 28 dfs(grid,x,y,visited); 29 } 30 } 31 } 32 };
DFS with recursion重点是对当前的节点进行什么操作,这里是把该节点标记成visited,loop四个方向的邻居,如果它们是‘1’并且没有被visited过,recursively call DFS on该邻居。
Note:
当然,也可以用unordered_set<pair<int,int>>来记录visited,只是比较麻烦,因为需要自己定义pair的哈希function。
unordered_set用
std::hash template来计算哈希值,里面没有说明pair的哈希值如何计算。
1 struct pair_hash {
2 inline size_t operator()(const pair<int,int> & v) const {
3 return v.first*31+v.second;
4 }
5 };
6
7 //Now you can use it like this:
8 unordered_set<pair<int, int>, pair_hash> visited;
1 struct pair_hash {
2 inline size_t operator()(const pair<int,int> & v) const {
3 return v.first*31+v.second;
4 }
5 };
6 class Solution {
7 public:
8 int numIslands(vector<vector<char>>& grid) {
9 if(grid.size()==0||grid[0].size()==0){
10 return 0;
11 }
12
13 unordered_set<pair<int,int>,pair_hash> visited;
14 int count = 0;
15 for(int i=0;i<grid.size();i++){
16 for(int j=0;j<grid[0].size();j++){
17 if(grid[i][j]=='1'&&visited.find(make_pair(i,j))==visited.end()){
18 visited.insert(make_pair(i,j));
19 count++;
20 dfs(grid,i,j,visited);
21 }
22 }
23 }
24 return count;
25 }
26 private:
27 void dfs(vector<vector<char>>&grid, int i, int j, unordered_set<pair<int,int>,pair_hash>&visited){
28 int dirs[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
29 for(auto dir: dirs){
30 int x = dir[0]+i;
31 int y = dir[1]+j;
32 if(x>=0&&y>=0&&x<grid.size()&&y<grid[0].size()&&grid[x][y]=='1'&&visited.find(make_pair(x,y))==visited.end()){
33 visited.insert(make_pair(x,y));
34 dfs(grid,x,y,visited);
35 }
36 }
37 }
38 };
浙公网安备 33010602011771号