LintCode-岛屿的个数

13 篇文章 0 订阅
433. 岛屿的个数

给一个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花了500多ms,人家都是几十ms搞定的,网上也没看到别的什么解法,用队列写了个BFS也没什么改善,很是怀疑评测机的性能。


DFS版:

class Solution {
public:
    /*
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
     vector<vector<bool>> grid;
     void DFS(const int& i,const int& j)
     {
         if(grid[i][j]==0) return;
         grid[i][j]=0;
         if(i>0) DFS(i-1,j);
         if(j>0) DFS(i,j-1);
         if(i<grid.size()-1) DFS(i+1,j);
         if(j<grid[0].size()-1) DFS(i,j+1);
     }
    int numIslands(vector<vector<bool>> &g) {
        // write your code here
        int count=0;
        grid=move(g);
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[i].size();j++)
            {
                if(grid[i][j]!=0) 
                {
                    DFS(i,j);
                    count++;
                }
            }
        }
        return count;
    }
};

BFS版:

class Solution {
public:
    /*
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
     vector<vector<bool>> grid;
     queue<pair<int,int>> q;
     void BFS(const int& i,const int& j)
     {
         q.push(pair<int,int>(i,j));
         while(!q.empty())
         {
             int i=q.front().first;
             int j=q.front().second;
             grid[i][j]=0;
             q.pop();
             if(i>0 && grid[i-1][j]!=0) q.push(pair<int,int>(i-1,j));
             if(j>0 && grid[i][j-1]!=0) q.push(pair<int,int>(i,j-1));
             if(i<grid.size()-1 && grid[i+1][j]!=0) q.push(pair<int,int>(i+1,j));
             if(j<grid[0].size()-1 && grid[i][j+1]!=0) q.push(pair<int,int>(i,j+1));
         }
     }
    int numIslands(vector<vector<bool>> &g) {
        // write your code here
        int count=0;
        grid=move(g);
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[i].size();j++)
            {
                if(grid[i][j]!=0) 
                {
                    BFS(i,j);
                    count++;
                }
            }
        }
        return count;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值