200. Number of Islands

来源:互联网 发布:开淘宝店的计划书 编辑:程序博客网 时间:2024/05/16 12:41

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

思路:这题就是图的遍历,可以用BSF和DSF,这里只写了BSF。遍历每个数字,如果为1,就变成不是1的数字,然后遍历与它上下左右相连的元素,为1的全部换成非1的数字,这样每次发现的新1都与原来的不相连,可以形成一个单独的island。最后count的为1的个数就是island的个数。

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



0 0
原创粉丝点击