leetcode-Number of Islands

来源:互联网 发布:list转换成byte数组 编辑:程序博客网 时间:2024/06/08 06:20

一、题目描述

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

二、思路分析

只需要利用bfs遍历一遍,遍历原则是,遇到为1时将其周围的1都设为0,其中遇到1的数量就是岛的数量。


三、代码

class Solution {public:    int numIslands(vector<vector<char> >& grid) {        int row = grid.size();        if (row == 0) {        return 0;        }        int col = grid[0].size();        if (col == 0) {        return 0;        }        int count = 0;        for (int i = 0; i < row; i++) {        for (int j = 0; j < col; j++) {        if (grid[i][j] == '1') {        bfs(grid, row, col, i, j);        count++;        }        }        }        return count;    }private:void bfs(vector<vector<char> >& grid, int row, int col, int i, int j) {if (i < 0|| j < 0|| i >= row|| j >= col||grid[i][j] == '0') {return;}        grid[i][j] = '0';bfs(grid, row, col, i+1, j);bfs(grid, row, col, i-1, j);bfs(grid, row, col, i, j-1);bfs(grid, row, col, i, j+1);}};


原创粉丝点击