LintCode-島嶼的個數

433. 島嶼的個數

給一個01矩陣,求不同的島嶼的個數。

0代表海,1代表島,如果兩個1相鄰,那麼這兩個1屬於同一個島。我們只考慮上下左右爲相鄰。

樣例

在矩陣:

[
  [1, 1, 0, 0, 0],
  [0, 1, 0, 0, 1],
  [0, 0, 0, 1, 1],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1]
]

中有 3 個島.


DFS花了500多ms,人家都是幾十ms搞定的,網上也沒看到別的什麼解法,用隊列寫了個BFS也沒什麼改善,很是懷疑評測機的性能。


DFS版:

class Solution {
public:
    /*
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
     vector<vector<bool>> grid;
     void DFS(const int& i,const int& j)
     {
         if(grid[i][j]==0) return;
         grid[i][j]=0;
         if(i>0) DFS(i-1,j);
         if(j>0) DFS(i,j-1);
         if(i<grid.size()-1) DFS(i+1,j);
         if(j<grid[0].size()-1) DFS(i,j+1);
     }
    int numIslands(vector<vector<bool>> &g) {
        // write your code here
        int count=0;
        grid=move(g);
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[i].size();j++)
            {
                if(grid[i][j]!=0) 
                {
                    DFS(i,j);
                    count++;
                }
            }
        }
        return count;
    }
};

BFS版:

class Solution {
public:
    /*
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
     vector<vector<bool>> grid;
     queue<pair<int,int>> q;
     void BFS(const int& i,const int& j)
     {
         q.push(pair<int,int>(i,j));
         while(!q.empty())
         {
             int i=q.front().first;
             int j=q.front().second;
             grid[i][j]=0;
             q.pop();
             if(i>0 && grid[i-1][j]!=0) q.push(pair<int,int>(i-1,j));
             if(j>0 && grid[i][j-1]!=0) q.push(pair<int,int>(i,j-1));
             if(i<grid.size()-1 && grid[i+1][j]!=0) q.push(pair<int,int>(i+1,j));
             if(j<grid[0].size()-1 && grid[i][j+1]!=0) q.push(pair<int,int>(i,j+1));
         }
     }
    int numIslands(vector<vector<bool>> &g) {
        // write your code here
        int count=0;
        grid=move(g);
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[i].size();j++)
            {
                if(grid[i][j]!=0) 
                {
                    BFS(i,j);
                    count++;
                }
            }
        }
        return count;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章