LeetCode--Number of Islands

来源:互联网 发布:东莞金拓软件 编辑:程序博客网 时间:2024/06/10 20:08

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:    int numIslands(vector<vector<char> >& grid) {        int count = 0, rows = grid.size(), cols = rows > 0 ? grid[0].size() : 0;        if (rows == 0 || cols == 0) return count;        bool visited[rows][cols];        queue<int> q;        int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};        int x = 0, y = 0, xx = 0, yy = 0;        for (int i = 0; i < rows; ++i)            for (int j = 0; j < cols; ++j) {                if (grid[i][j] == '1' && !visited[i][j]) {                    q.push(i);                    q.push(j);                    visited[i][j] = true;                    ++count;                    while (!q.empty()) {                        x = q.front();                         q.pop();                        y = q.front();                        q.pop();                        for (int k = 0; k < 4; ++k) {                            xx = x + dx[k];                            yy = y + dy[k];                            if (xx < 0 || xx >= rows || yy < 0 || yy >= cols)                                continue;                            if (grid[xx][yy] == '1' && !visited[xx][yy]) {                                visited[xx][yy] = true;                                q.push(xx);                                q.push(yy);                            }                        }                    }                }            }        return count;    }};

这里要说明的就是我们的这个队列queue<int> q每次要push进去两个元素,分别代表横坐标和纵坐标。当然队列中被访问过的位置出队的时候也要进行两次pop操作。每一次进行到新的一次for循环的时候如果当前遍历到的位置之前没被访问过且这个位置是陆地,那么这个位置就会作为一个新的岛屿的最初的地带,然后这个位置还要被标记为已访问过。

我认为思路还有很多,比如说我们可以把两重for循环改成只有一重for循环,就是把二维坐标转换成一维坐标(4*row+col),但是这样的话在广度优先搜索的过程中要将一维坐标重新转换为二维坐标,因为题目规定传入的参数是二维向量,所以还是比较麻烦的。总之本题不是很难,比较基础。