您的位置:首页 > 其它

[LeetCode] 200. Number of Islands 解题思路

2016-01-10 20:26 579 查看
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 的区域块块数。

unordered_map<string, pair<int, int>> val_pos;
vector<vector<char>> theGrid;

/**
* remove all land connecting with [i, k] adjecent horizontally or vertically. and the pos.
*/
void removeLand(int i, int k){

theGrid[i][k] = '0';

string str = to_string(i) + "_" + to_string(k);
val_pos.erase(str);

if (i-1 >= 0 && theGrid[i-1][k] == '1'){
removeLand(i-1, k);
}

if (k+1 < theGrid[0].size() && theGrid[i][k+1] == '1'){
removeLand(i, k+1);
}

if (i+1 < theGrid.size() && theGrid[i+1][k] == '1'){
removeLand(i+1, k);
}

if (k-1 >= 0 && theGrid[i][k-1] == '1'){
removeLand(i, k-1);
}
}

int numIslands(vector<vector<char>>& grid) {

if (grid.size() == 0){
return 0;
}

theGrid = grid;
for ( int i = 0 ; i < grid.size(); i++){
for(int k = 0 ; k < grid[0].size(); k++){
if (grid[i][k] == '1'){
string str = to_string(i) + "_" + to_string(k);
val_pos[str] = {i, k};
}
}
}

int res = 0;

while(val_pos.size() > 0 ){
int i = val_pos.begin()->second.first;
int k = val_pos.begin()->second.second;
removeLand(i, k);
res++;
}

return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: