[LeetCode] 200. Number of Islands 解题思路
2016-01-10 20:26
579 查看
Given a 2d grid map of
Example 1:
Answer: 1
Example 2:
Answer: 3
问题:找出矩阵中前后左右相邻为 1 的区域块块数。
属于 DFS 思想。
将所有 1 塞进一个容器中,从容器中取出一个 1 ,并将相邻走完的 1 也从容器中取出,视为一次取数。重复此操作直至容器中没有元素 1 ,则取出次数就是 1 的区域块块数。
'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; }
相关文章推荐
- zzulioj--1613--少活一年?(稍微有点坑,水!)
- 内存寻址原理
- gnuradio之flowgraph和top_block
- iphone 添加qq邮箱.
- cocos2d-js使用plist执行自身动作
- iOS开发实践之xib加载注意问题
- zzulioj--1613--少活一年?(稍微有点坑,水!)
- awk用法总结
- 使用.NET进行高效率互联网敏捷开发的思考和探索【一、概述】
- TCP粘包分析
- iOS 支付宝集成
- 【Android】Android 基础知识
- 如何使用STM32提供的DSP库进行FFT
- CSS3学习笔记(4)-CSS3函数
- 【转载】Apache Kafka监控之Kafka Web Console
- opencv小练习:哈尔小波(Haar)
- 新手自定义控件,创建属于自己的下拉刷新(一)---Android,ListView实现IOS的弹性效果
- Mac OS install mongodb
- HDOJ 1406 完数
- 【html】What is href=“#” and why is it used?