博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Number of Islands
阅读量:6956 次
发布时间:2019-06-27

本文共 2308 字,大约阅读时间需要 7 分钟。

This is a typical problem about searching. In fact, you can use either BFS or DFS for it. Personally, I use BFS because I think it is more intuitive and easy to implement.

The idea is fairly simple. We maintain another 2-dimensional vector visited to mark whether the corresponding position in grid has been visited and a variable count for the number of islands (initialized to be 0). Then we visit grid from left to right and top to bottom. Each time when we see a non-visited 1 in grid, we add the number of islands by 1 and mark all the connected 4-neighbors (BFS is applied here to get neighbors, neighbors of neighbors, neighbors of neighbors of neighbors, ...) of the non-visited 1 (including itself) as visited.

Note that a lot of the solutions in the discussion forum directly changes 1 in grid to 0 instead of using another 2-dimensional vector visited. However, I personally prefer to keep the input unchanged in a function with a return value.

The code is as follows.

1 class Solution { 2 public: 3     int numIslands(vector
>& grid) { 4 if (grid.empty()) return 0; 5 int m = grid.size(), n = grid[0].size(); 6 vector
> visited(m, vector
(n, false)); 7 int count = 0; 8 for (int i = 0; i < m; i++) { 9 for (int j = 0; j < n; j++) {10 if (grid[i][j] == '1' && !visited[i][j]){11 count++;12 markIslands(grid, visited, i, j);13 }14 }15 }16 return count;17 }18 private:19 void markIslands(vector
>& grid, vector
>& visited, int row, int col) {20 visited[row][col] = true;21 if (row - 1 >= 0 && grid[row - 1][col] == '1' && !visited[row - 1][col])22 markIslands(grid, visited, row - 1, col);23 if (row + 1 < grid.size() && grid[row + 1][col] == '1' && !visited[row + 1][col])24 markIslands(grid, visited, row + 1, col);25 if (col - 1 >= 0 && grid[row][col - 1] == '1' && !visited[row][col - 1])26 markIslands(grid, visited, row, col - 1);27 if (col + 1 < grid[0].size() && grid[row][col + 1] == '1' && !visited[row][col + 1])28 markIslands(grid, visited, row, col + 1);29 }30 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4596231.html

你可能感兴趣的文章
JavaScript数组去重总结
查看>>
MVVM_Android-CleanArchitecture
查看>>
iOS开发-协议Protocol&代理delegate
查看>>
【系统架构师修炼之道】(4):绪论——Zachman 框架
查看>>
Foxify v0.10.7 发布,基于 TypeScript 的 Node 框架
查看>>
Python数据结构——双端队列
查看>>
GitHub 项目推荐:用深度学习让你的照片变得美丽 ...
查看>>
另类文件加密 图片当密码给文本加密
查看>>
MySQL数据库如何解决大数据量存储问题
查看>>
CENTOS6.5 yum配置
查看>>
《自顶向下网络设计(第3版)》——1.6 复习题
查看>>
【转】微信小程序给程序员带来的可能是一个赚钱的机遇
查看>>
《Programming Ruby中文版:第2版》终于正式出版了
查看>>
使用Observium来监控你的网络和服务器
查看>>
蚂蚁区块链团队资讯简报20170514
查看>>
线性空间(向量空间)
查看>>
多媒体之录音
查看>>
mysql 分区类型详解
查看>>
ORACLE同义词总结
查看>>
ios字体设置
查看>>