[Leetcode]Number of Islands

来源:互联网 发布:阿里云怎么安装软件 编辑:程序博客网 时间:2024/06/05 11:29

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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

class Solution {public:    /*algorithm: BFS     1)if grid[i][j] is '1', count++,BFS search from (i,j),mark them to '#'     2)scan grid row by row     time O(m*n), space O(1)    */    void bfs(vector<vector<char>>& grid,int x,int y,int m,int n){        if(x < 0 || x >= m ||y < 0 || y >= n)return;        if(grid[x][y] == '1'){            grid[x][y] = '#';            bfs(grid,x-1,y,m,n);//top            bfs(grid,x,y+1,m,n);//right            bfs(grid,x+1,y,m,n);//down            bfs(grid,x,y-1,m,n);//left        }    }    int numIslands(vector<vector<char>>& grid) {        int m = grid.size();        if(m < 1)return 0;        int n = grid[0].size();        if(n < 1)return 0;        int cnt = 0;        for(int r = 0;r < m;r++){            for(int c = 0;c < n;c++){                if(grid[r][c] == '1'){                    ++cnt;                    bfs(grid,r,c,m,n);                }            }        }        return cnt;    }};


0 0
原创粉丝点击