lintcode433 岛屿的个数
生活随笔
收集整理的這篇文章主要介紹了
lintcode433 岛屿的个数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
島嶼的個數?
給一個01矩陣,求不同的島嶼的個數。
0代表海,1代表島,如果兩個1相鄰,那么這兩個1屬于同一個島。我們只考慮上下左右為相鄰。
您在真實的面試中是否遇到過這個題?? Yes 樣例在矩陣:
[[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?個島.
?
1 class Solution { 2 public: 3 /** 4 * @param grid a boolean 2D matrix 5 * @return an integer 6 */ 7 int numIslands(vector<vector<bool>>& grid) { 8 // Write your code here 9 if(grid.empty() || grid[0].empty()) 10 return 0; 11 int m = grid.size(), n = grid[0].size(); 12 int count = 0; 13 for(int i = 0; i < m; ++i){ 14 for(int j = 0; j < n; ++j){ 15 if(grid[i][j]){ 16 ++count; 17 dfs(grid, i, j); 18 } 19 } 20 } 21 return count; 22 } 23 void dfs(vector<vector<bool> > &grid, int x, int y){ 24 if((x < 0) || (y < 0) || (x >= grid.size()) || (y >= grid[0].size()) || !grid[x][y]) 25 return; 26 grid[x][y] = false; 27 dfs(grid, x - 1, y); 28 dfs(grid, x, y - 1); 29 dfs(grid, x + 1, y); 30 dfs(grid, x, y + 1); 31 } 32 };?
轉載于:https://www.cnblogs.com/gousheng/p/7635002.html
總結
以上是生活随笔為你收集整理的lintcode433 岛屿的个数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归 和 迭代 斐波那契数列
- 下一篇: bash 的相关配置