题解 | #岛屿数量#

岛屿数量

http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e

深度优先遍历DFS:

class Solution {
public:
    /**
     * 判断岛屿数量
     * @param grid char字符型vector<vector<>> 
     * @return int整型
     */
    void dfs(int x, int y, vector<vector<char> > &grid, vector<vector<int> > & mark, int r, int c) {
        if (x < 0 || x >= r || y < 0 || y >= c || mark[x][y] == 0) return; //越界或已标记
        if (grid[x][y] == '1') {
            mark[x][y] = 0; // 标记为0
            // 向上下左右四个方向查找
            dfs(x+1, y, grid, mark, r, c);
            dfs(x-1, y, grid, mark, r, c);
            dfs(x, y+1, grid, mark, r, c);
            dfs(x, y-1, grid, mark, r, c);
        }
    }


    int solve(vector<vector<char> >& grid) {
        // write code here
        if (grid.empty()) return 0;
        int r = grid.size();
        int c = grid[0].size();
        int count = 0;
        vector<vector<int> > mark(r, vector<int>(c,1));  // 记录是否遍历过
        for (int i = 0; i < r; ++i) {
            for (int j = 0; j < c; ++j) {
                if (grid[i][j] == '1' && mark[i][j]) {
                    dfs(i, j, grid, mark, r, c);
                    count++;  // 增加岛屿数
                }
            }
        }
        return count;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务