Lintcode解题笔记 - 岛屿的个数

原文链接: http://www.lintcode.com/zh-cn/problem/number-of-islands/

给一个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 个岛.

思路一:
使用一个辅助数组,visited[][],大小和原数组gird相同,遍历grid数组,如果对应元素grid[i][j]在visited中也没有访问,则将visited[i][j]设置为1, 然后遍历visited[i][j]的上下左右4个元素。

使用辅助的floodRush函数,该函数用于判断/设定visited[i][j]的值,然后递归遍历visited[i][j]上下左右4个元素

该解法在第8个case时候,遇到超时问题,可能是时间复杂度过高

class Solution {
public:
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    int numIslands(vector<vector<bool>>& grid) {
        // Write your code here
        int row = grid.size();
        if(row < 1)
            return 0;
        int column = grid[0].size();
        vector<int> tmp(column, 0);
        vector<vector<int>> visited(row, tmp); 
        //int visited[row][column] = 0;
        //vector<vector<bool>> visited = grid;
        int result = 0;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < column; j++ ){
                if(grid[i][j] == true && visited[i][j] != 1){
                    floodRush(i,j, visited, grid);
                    result++;
                }

            }
        }
        return result;



    }


    void floodRush(int row, int column, vector<vector<int>> & visited, vector<vector<bool>> grid){
        if(row < 0 || column < 0 || row >= grid.size() || column >= grid[0].size() ){
            return;
        }
        if(visited[row][column] == 1)
            return;
        if(grid[row][column] == true){
            visited[row][column] = 1;
            floodRush(row-1, column, visited, grid);
            floodRush(row+1, column, visited, grid);
            floodRush(row, column-1, visited, grid);
            floodRush(row, column+1, visited, grid);
        }else{
            return;
        }



    }

};

几个总结,传递以为数组时候,可以使用void A(int a[]),但传递二维数组的时候,需要使用A(int a[][xxx]),来传递。因为编译器需要之后二维数组中某一维度的深度。 参见http://www.cplusplus.com/doc/tutorial/arrays/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值