200. Number of Islands

来源:互联网 发布:淘宝4钻 编辑:程序博客网 时间:2024/05/16 05:21

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

这是一个典型的floodfill算法。

解题代码

class Solution {private:    int m, n; // m行,n列    // 上右下左4个方向的偏移    int direction[4][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };    vector<vector<bool>> visited;    bool isInArea(int x, int y){        return x >= 0 && x < m && y >= 0 && y < n;    }    void dfs(const vector<vector<char>>& grid, int x, int y){        //int direction[4][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };        visited[x][y] = true;        for (int i = 0; i < 4; i++)        {            int nextX = x + direction[i][0];            int nextY = y + direction[i][1];            if (isInArea(nextX, nextY) && !visited[nextX][nextY] && grid[nextX][nextY] == '1')                dfs(grid, nextX, nextY);        }        return;    }public:    int numIslands(vector<vector<char>>& grid) {        m = grid.size();        if (m == 0)return 0;        n = grid[0].size();        visited = vector <vector<bool>>(m, vector<bool>(n, false));        int res = 0;// 岛屿的个数        for (int i = 0; i < m; i++)        for (int j = 0; j < n; j++){            if (grid[i][j] == '1' && !visited[i][j])            {                res++;                dfs(grid, i, j);            }        }        return res;    }};

工具

namespace Utils {    // 显示vector信息    void showVecInfo(vector<string> & v) {        cout << endl << "vector : [ " <<endl;        for (vector<string>::iterator it = v.begin(); it != v.end(); it++)        {            cout << "\t\t" << *it << endl;        }        cout << "         ]" << endl;    }    void get2Dstr(const vector<string> &s, vector<vector<char>> &board){        for (int i = 0; i < s.size(); i++)        {            vector<char> v;            for (int j = 0; j < s[i].size(); j++)            {                v.push_back(s[i][j]);            }            board.push_back(v);        }    }}

测试

class TestHelper{    Solution s;public:    void run(){        string grid[] = {"11110","11010","11000","00000"};        int len = 4;        vector<string> v(grid, grid + len);        vector<vector<char>> gridCh;        Utils::get2Dstr(v, gridCh);        Utils::showVecInfo(v);        cout<<"Num of Islands is : " << s.numIslands(gridCh) <<endl;    }};

结果

vector : [                11110                11010                11000                00000         ]Num of Islands is : 1请按任意键继续. . .
原创粉丝点击