200. Number of Islands

題目

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

思路

這道題目搞了我很久,主要是一邊解題一般玩了,這其實也是個典型的union-find題目,我們首先要將數組裏面的兩兩之間的連通分量求出來,再利用我們前一篇博客的解法求連通數。

代碼

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.size()==0)
            return 0;
        int m = grid.size();
        int n = grid[0].size();
        int num1=0;
        vector<int> tmp(2);
        vector<vector<int>> res;
        //第一次遍歷矩陣將字符轉換成整數
        vector<vector<int>> matrixs;
        for(int i=0;i<m;i++){
            vector<int> matrix;
            for(int j=0;j<n;j++)
            {

                matrix.push_back(grid[i][j]-48);
            }
            matrixs.push_back(matrix);
        }
        cout<<matrixs[0][1]<<endl;   
        //第二次遍歷矩陣,統計有幾個1,並賦值
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                if(matrixs[i][j]==1)
                {
                    num1++;
                    matrixs[i][j] = num1;
                }
            }
        //第三次遍歷,尋找大小爲2的連通分量,並存儲到數組裏
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                if(matrixs[i][j]==0)
                    continue;
                else
                {
                    tmp[1] = matrixs[i][j];
                    if(matrixs[i][max(j-1,0)]!=0)
                    {
                        tmp[0] =matrixs[i][max(j-1,0)];
                        res.push_back(tmp);
                    }
                    if(matrixs[max(i-1,0)][j]!=0)
                    {
                        tmp[0] =matrixs[max(i-1,0)][j];
                        res.push_back(tmp);
                    }
                    if(matrixs[i][max(j-1,0)]==0&&matrixs[max(i-1,0)][j]==0)
                    {
                        tmp[0] =matrixs[i][j];
                        res.push_back(tmp);  
                    }


                }
            }

        vector<int> M(num1+1);
        for(int i=0;i<num1+1;i++)
            M[i] = i;
        for(auto item:res)
        {
            int p = item[0];
            int q = item[1];
            while(p!=M[p])
                p = M[p];
            while(q!=M[q])
                q = M[q];
            if(p!=q)
            {
                M[q] = p;
                num1--;
            }


        }
        return num1;
    }
};
發佈了310 篇原創文章 · 獲贊 520 · 訪問量 70萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章