class Solution { public: void dfs(vector<vector<int>>& A,int i,int j){ if(i<0||i>=A.size()||j<0||j>=A[0].size())return; if(A[i][j]==1) A[i][j]=2; else return; dfs(A,i+1,j); dfs(A,i-1,j); dfs(A,i,j+1); dfs(A,i,j-1); } bool bfs(vector<vector<int>>& A,set<pair<int,int> >&v){ set<pair<int,int> >vvv=set<pair<int,int> >(v); for(auto vv:vvv){ if((vv.second+1<A[0].size()&&A[vv.first][vv.second+1]==2)||(vv.second-1>=0&&A[vv.first][vv.second-1]==2)||(vv.first-1>=0&&A[vv.first-1][vv.second]==2)||(vv.first+1<A.size()&&A[vv.first+1][vv.second]==2)) return 1; if(vv.second+1<A[0].size()&&A[vv.first][vv.second+1]==0){A[vv.first][vv.second+1]=1;v.insert(make_pair(vv.first,vv.second+1));} if(vv.second-1>=0&&A[vv.first][vv.second-1]==0){A[vv.first][vv.second-1]=1;v.insert(make_pair(vv.first,vv.second-1));} if(vv.first+1<A.size()&&A[vv.first+1][vv.second]==0){A[vv.first+1][vv.second]=1;v.insert(make_pair(vv.first+1,vv.second));} if(vv.first-1>=0&&A[vv.first-1][vv.second]==0){A[vv.first-1][vv.second]=1;v.insert(make_pair(vv.first-1,vv.second));} v.erase(vv); } return 0; } int shortestBridge(vector<vector<int>>& A) { int i,j,p,q; for( i=0;i<A.size();i++){ for( j=0;j<A[0].size();j++){ if(A[i][j]==0)continue; else {p=i;q=j;break;} } } dfs(A,p,q); set<pair<int,int> >v; for(i=0;i<A.size();i++){ for(j=0;j<A[0].size();j++){ if(A[i][j]==1){v.insert(make_pair(i,j));} } } int ans=0; while(!bfs(A,v)){ans++;} return ans; } };
找到一个'1'后,dfs(上下左右)找出所有相连。
找出第二座岛的所有序号,放在一个set里,每次往外拓展一层,直到碰到第一座岛