【Leetcode】200. Number of Island

来源:互联网 发布:unity3d awake 编辑:程序博客网 时间:2024/05/29 16:36

Description:

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:

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011
Answer: 3

思路:

本题需要判断二维数组中相连的’1’的块数,这里可以直观地使用DFS来找出所有块。从左上的起始点出发,对其上下左右4个点进行判断,如果是’1’且在范围内那么就继续搜寻下去,否则就什么都不做。另外,为了对已经搜寻过的点进行标记,同时最大程度节省空间,可以直接在原二维数组中操作,将访问过的’1’变为’0’。每次成功完成一次连续的搜寻,则count++,最后便可以找出结果。

以下是使用C++的实现过程:

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'){                    dfs(grid, i, j);                    count++;                }            }        }        return count;    }    void dfs(vector<vector<char> >& grid, int i, int j){        if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]!='1') return;        grid[i][j] = '0';        dfs(grid,i+1,j);        dfs(grid,i-1,j);        dfs(grid,i,j+1);        dfs(grid,i,j-1);    }};
原创粉丝点击