首页 > 其他 > 详细

200. Number of Islands

时间:2018-10-13 23:52:55      阅读:217      评论:0      收藏:0      [点我收藏+]

错误版本:

    条件判断顺序写错:grid[x][y] == ‘0‘ || x < 0 || x >= length || y < 0 || y >= width

    这种写法要报数组越界的错误,因为grid[x][y]会先访问,实际上x、y这个时候可能就越界了,grid[x][y]必须放在这几个越界判断的后面

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int length = grid.size();
        if(length <= 0)
            return 0;
        int width = grid[0].size();
        int count = 0;
        for(int i = 0;i < length;i++){
            for(int j = 0;j < width;j++){
                if(grid[i][j] == 1){
                    search(grid,i,j,length,width);
                    count++;
                }
            }
        }
        return count;
    }
    void search(vector<vector<char>>& grid,int x,int y,int length,int width){
        if(x < 0 || x >= length || y < 0 || y >= width || grid[x][y] == 0)
            return;
        grid[x][y] = 0;
        search(grid,x-1,y,length,width);
        search(grid,x+1,y,length,width);
        search(grid,x,y-1,length,width);
        search(grid,x,y+1,length,width);
    }
};

 

 

整体思路,从第一点开始找1,如果找到1,把所有的与这个1相连的1置为0,因为这些1与这个1属于同一个岛屿,用dfs去找把所有的1找到

https://blog.csdn.net/xudli/article/details/45912547

200. Number of Islands

原文:https://www.cnblogs.com/ymjyqsx/p/9784453.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!