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:
1 2 3 4
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:
1 2 3 4
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.
classSolution { public: intnumEnclaves(vector<vector<int>>& A){ int m = A.size(); int n = A[0].size(); queue<pair<int, int>> q; int dx[] = {0, -1, 0, 1}; int dy[] = {-1, 0, 1, 0}; // check boundary for (int i = 0; i < m; i++) { if (A[i][0] == 1) { A[i][0] = -1; } if (A[i][n - 1] == 1) { A[i][n - 1] = -1; } } for (int i = 0; i < n; i++) { if (A[0][i] == 1) { A[0][i] = -1; } if (A[m - 1][i] == 1) { A[m - 1][i] = -1; } } // BFS for (int i = 0 ; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == -1) { q.push(make_pair(i, j)); while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); for (int k = 0; k < 4; k++) { int x = dx[k] + p.first; int y = dy[k] + p.second; if (x >= 0 && x < m && y >= 0 && y < n && A[x][y] == 1) { A[x][y] = -1; q.push(make_pair(x, y)); } } } } } } // count 1s in grid int result = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == 1) { result++; } } } return result; } };