[LeetCode] 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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

 问题:找出矩阵中前后左右相邻为 1 的区域块块数。

属于 DFS 思想。

将所有 1 塞进一个容器中,从容器中取出一个 1 ,并将相邻走完的 1 也从容器中取出,视为一次取数。重复此操作直至容器中没有元素 1 ,则取出次数就是 1 的区域块块数。

 1     unordered_map<string, pair<int, int>> val_pos;
 2     vector<vector<char>> theGrid;
 3 
 4 
 5     /**
 6      * remove all land connecting with [i, k] adjecent horizontally or vertically. and the pos.
 7      */
 8     void removeLand(int i, int k){
 9         
10         theGrid[i][k] = '0';
11         
12         string str = to_string(i) + "_" + to_string(k);
13         val_pos.erase(str);
14         
15         if (i-1 >= 0 && theGrid[i-1][k] == '1'){
16             removeLand(i-1, k);
17         }
18         
19         if (k+1 < theGrid[0].size() && theGrid[i][k+1] == '1'){
20             removeLand(i, k+1);
21         }
22         
23         if (i+1 < theGrid.size() && theGrid[i+1][k] == '1'){
24             removeLand(i+1, k);
25         }
26         
27         if (k-1 >= 0 && theGrid[i][k-1] == '1'){
28             removeLand(i, k-1);
29         }
30     }
31 
32     int numIslands(vector<vector<char>>& grid) {
33         
34         if (grid.size() == 0){
35             return 0;
36         }
37 
38         theGrid = grid;
39         for ( int i = 0 ; i < grid.size(); i++){
40             for(int k = 0 ; k < grid[0].size(); k++){
41                 if (grid[i][k] == '1'){
42                     string str = to_string(i) + "_" + to_string(k);
43                     val_pos[str] = {i, k};
44                 }
45             }
46         }
47         
48         int res = 0;
49         
50         while(val_pos.size() > 0 ){
51             int i = val_pos.begin()->second.first;
52             int k = val_pos.begin()->second.second;
53             removeLand(i, k);
54             res++;
55         }
56         
57         return res;
58     }
原文地址:https://www.cnblogs.com/TonyYPZhang/p/5119062.html