欢迎来到PJCK的博客

(BFS 图的遍历) leetcode 1020. Number of Enclaves

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

 

Example 1:

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: 
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.

Example 2:

Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: 
All 1s are either on the boundary or can reach the boundary.

 

Note:

  1. 1 <= A.length <= 500
  2. 1 <= A[i].length <= 500
  3. 0 <= A[i][j] <= 1
  4. All rows have the same size.

 

这个题是BFS模板题,也可以用DFS,不过题的标签是只有DFS的。。。。。。

在BFS上,就是先遍历图的边界,如果是1,就把它更新为2(除了0和1,什么数都行),然后开始遍历,如果碰上2,加入队列,然后在更新队列中,如果碰上1,把它更新为2,然后加入队列,直到队列为空,最后再次遍历,统计1的个数。emmmm,48ms就能打败96%多点(C++上)。

 

 

C++代码:

int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
class Solution {
public:
    typedef pair<int,int> pii;
    queue<pii> q;
    int numEnclaves(vector<vector<int>>& A) {
        int m = A.size();
        int n = A[0].size();
        for(int i = 0; i < m; i++){
            if(A[i][0] == 1)
                A[i][0] = 2;
            if(A[i][n-1] == 1)
                A[i][n-1] = 2;
        }
        for(int j = 0; j < n; j++){
            if(A[0][j] == 1){
                A[0][j] = 2;
            }
            if(A[m-1][j] == 1){
                A[m-1][j] = 2;
            }
        }
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(A[i][j] == 2){
                    q.push(make_pair(i,j));
                    while(!q.empty()){
                        auto t = q.front();q.pop();
                        for(int i = 0;i < 4; i++){
                            int x = t.first + dx[i];
                            int y = t.second + dy[i];
                            if(x >= 0 && x < m && y >= 0 && y < n && A[x][y] == 1){
                                q.push(make_pair(x,y));
                                A[x][y] = 2;
                            }
                        }
                    }
                }
            }
        }
        int cnt = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(A[i][j] == 1)
                    cnt++;
            }
        }
        return cnt;
    }
};

 

posted @ 2019-05-15 21:19  PJCK  阅读(36)  评论(0编辑  收藏