总结:还是利用广搜或者深搜,此题的重点是在广搜的同时需要记录下不能离开边界的数量,我的想法是利用一个count和一个bool来记录,如果在广搜的过程中发现有岛的下标在边界上的则bool为真,且将0加入vector中,否则将count累加,直至这一片搜索完成,最后再将vector中的数累加返回,其中容易遗忘的点是需要在将0加入vector之后要将bool设置为假,否则将会导致后面的一片区域都是bool为真而都是0 ;
代码:
- class Solution {
- public:
- int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
- vector<int> res;
- bool flag = false;
- void bfs(vector
int >>& grid, vectorbool >>& visited,int x,int y) - {
- queue
int,int>> que; - que.push(pair{x,y});
- visited[x][y] = true;
- int count = 0;
- if(x == grid.size() - 1 || y == grid[0].size() - 1 || x == 0 || y == 0)
- {
- flag = true;
- }
- else count++;
- while(!que.empty())
- {
- auto cur = que.front();
- que.pop();
- int curx = cur.first;
- int cury = cur.second;
- for(int i = 0;i < 4;i++)
- {
- int nextx = curx + dir[i][0];
- int nexty = cury + dir[i][1];
- if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size())
- continue;
- if(grid[nextx][nexty] == 1 && visited[nextx][nexty] != true)
- {
- que.push(pair{nextx,nexty});
- visited[nextx][nexty] = true;
- if(nextx == grid.size() - 1 || nexty == grid[0].size() - 1 || nextx == 0 || nexty == 0)
- {
- flag = true;
- }
- else count++;
- }
- }
- }
- if(flag == true)
- {
- res.push_back(0);
- flag = false;
- }
- else res.push_back(count);
- }
- int numEnclaves(vector
int >>& grid) { -
- int n = grid.size();
- int m = grid[0].size();
- vector
bool>> visited(n,vector<bool>(m,false)); - for(int i = 0;i < n;i++)
- {
- for(int j = 0;j < m;j++)
- {
- if(grid[i][j] == 1 && visited[i][j] != true)
- {
- bfs(grid,visited,i,j);
- }
- }
- }
- int sum = 0;
- for(int i = 0;i < res.size();i++)
- {
- sum += res[i];
- }
- return sum;
- }
- };