海岛个数问题LintCode
2017-05-09 22:40
453 查看
笔试编程题
问题描述:给一个01矩阵,求不同的岛屿的个数。
0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
样例
在矩阵:
[ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ]
总共有3个海岛。
求解:采用深搜(DFS)策略:
遍历过的元素置为false;
void DFS(vector<vector<bool>>& grid,int i,int j){ grid[i][j] = 0; if(i>0&&grid[i-1][j]) DFS(grid,i-1,j); if(j>0&&grid[i][j-1]) DFS(grid,i,j-1); if(i<grid.size()-1 && grid[i+1][j]) DFS(grid,i+1,j); if(j<grid[0].size()-1 && grid[i][j+1]) DFS(grid,i,j+1); } int numIslands(vector<vector<bool>>& grid) { int count = 0; for(int i = 0;i<grid.size();i++){ for(int j = 0;j<grid[0].size();j++){ if(grid[i][j]) { DFS(grid,i,j); count++; } } } return count; }
相关文章推荐
- LintCode : 背包问题 II
- 海岛问题
- lintcode之Wood-Cut问题
- LintCode(M)背包问题
- 【lintcode】1、A+B问题【位运算】
- LintCode(M)背包问题2
- [LintCode] Parking Lot 停车场问题
- lintcode-N-Queen, N皇后问题
- Lintcode 1 A + B 问题
- LintCode-背包问题 II
- lintcode 中等题:N Queens N皇后问题
- LintCode_9_Fizz Buzz 问题
- lintcode:背包问题II
- LintCode-剑指Offer-(1)A+B问题
- [LintCode] A + B 问题
- 【LintCode】 Backpack II 背包问题II
- lintcode- N皇后问题
- LintCode(easy)旋转字符串(!!!我有史以来解决的问题最快的一次,心酸流泪)
- LintCode-第1题 A+B问题
- LintCode:01背包问题