1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class Solution { int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; vector<vector<int>> grid_d; int n,m; public: int closedIsland(vector<vector<int>>& grid) { n=grid.size(),m=grid[0].size(); this->grid_d=grid; int res=0; vector<vector<bool>> used(n,vector<bool>(m,false));
for(int i=1;i<n-1;i++) { for(int j=1;j<m-1;j++) { if(grid[i][j]!=1&&!used[i][j]) { used[i][j]=true; res+=bfs(i,j,used); } } } return res; } int bfs(int i,int j,vector<vector<bool>>& used) { queue<pair<int,int>> que; que.push(make_pair(i,j)); int ret=1; while(!que.empty()) { int size=que.size(); for(int k=0;k<size;k++) { pair<int,int> q=que.front();que.pop(); int x=q.first,y=q.second; for(int d=0;d<4;d++) { if(x+dir[d][0]>=0&&x+dir[d][0]<n&&y+dir[d][1]>=0&&y+dir[d][1]<m&&grid_d[x+dir[d][0]][y+dir[d][1]]!=1&&!used[x+dir[d][0]][y+dir[d][1]]) { int newx=x+dir[d][0],newy=y+dir[d][1]; used[newx][newy]=true; if((newx==0||newx==n-1||newy==0||newy==m-1)&&grid_d[newx][newy]==0) { ret=0; } que.push(make_pair(newx,newy)); } } } } return ret; } };
|