200. Number of Islands(DFS or BFS)

来源:互联网 发布:劳动收入份额数据 编辑:程序博客网 时间:2024/06/05 00:48

一、问题描述

写在前面:深度优先搜索和广度优先搜索在实际问题中的应用,特别是在矩阵上的BFS和DFS的应用。

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

二、算法与代码

DFS解法:只要先找到一个’1’,然后往它的四个方向递归,递归过程遇到’1’就将其置为‘0’,这样,找完一个“岛”之后,所有在同一个“岛”上的‘1’就全被置为‘0’了,这样,在O(n3)的时间内能找出所有“岛”,因为DFS的时间复杂度为O(n)

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

BFS解法:类似的,只要先找到一个’1’,将其上下左右可能的相邻的‘1’入队,接着按照队里的‘1’去找其相邻的‘1’,将找到的相邻的‘1’置为‘0’,只要队里为空,即“岛”增加一个。

class Solution{public:    int numIslands(vector<vector<char>> &grid) {        if(grid.size() == 0 || grid[0].size() == 0)            return 0;            int res = 0;            for(int i = 0; i < grid.size(); ++ i)                for(int j = 0; j < grid[0].size(); ++ j)                     if(grid[i][j] == '1'){                         ++ res;                         BFS(grid, i, j);                 }             return res;     }private:    void BFS(vector<vector<char>> &grid, int x, int y){        queue<vector<int>> q;        q.push({x, y});        grid[x][y] = '0';         while(!q.empty()){             x = q.front()[0], y = q.front()[1];             q.pop();             if(x > 0 && grid[x - 1][y] == '1'){                 q.push({x - 1, y});                 grid[x - 1][y] = '0';             }             if(x < grid.size() - 1 && grid[x + 1][y] == '1'){                 q.push({x + 1, y});                 grid[x + 1][y] = '0';             }             if(y > 0 && grid[x][y - 1] == '1'){                 q.push({x, y - 1});                 grid[x][y - 1] = '0';             }             if(y < grid[0].size() - 1 && grid[x][y + 1] == '1'){                 q.push({x, y + 1});                 grid[x][y + 1] = '0';             }         }     }};
原创粉丝点击