2维0,1矩阵。判断有多少个封闭的全是0的area。DFS,BFS的方法都要写。
void dfs(const vector<vector<int>> &G, int i, int j){
if(i<0 || i >= rown || j<0 || j >= coln) return;
if(G[i][j] == 1 || visited[i][j] == 1) return;
visited[i][j] = 1;
dfs(G, i - 1, j);
dfs(G, i + 1, j);
dfs(G, i, j+1);
dfs(G, i, j-1);
}
int count(vector<vector<int>>G){
if(G.empty()) return 0;
int count;
int rown = G.size(), coln = G[0].size;
vector<vector<int>> visited(rown, vector<int>(coln,0));
for(i = 0; i < rown; i++) {
for(j = 0; j < coln; j++){
if(visited[i][j] == 0&& G[i][j] == 0) {
count++;
dfs(G,i, j, rown, coln);
}
}
}
return count;
}
-------------------
void bfs(const vector<vector<int>> &G, int i, int j){
queqe<pair<int,int>> q;
q.push(make_pair(i,j));
while(!q.empty()){
i = queue.front().first; j = queue.front().second;
queue.pop();
visited[i][j] = 1;
if(i > 0 && visited[i-1][j] == 0 && G[i-1][j] == 0) queue.push(make_pair(i-1,j));
if(j> 0 && visited[i][j-1] == 0 && G[i][j-1] == 0) queue.push(make_pair(i,j-1));
if(i < rown - 1 && visited[i+1][j] == 0 && G[i+1][j] == 0) queue.push(make_pair(i+1,j));
if(j < coln - 1 && visited[i][j+1] == 0&& G[i][j+1] == 0) queue.push(make_pair(i,j+1));
}
}
int count(vector<vector<int>>G){
if(G.empty()) return 0;
int count;
int rown = G.size(), coln = G[0].size;
vector<vector<int>> visited(rown, vector<int>(coln,0));
for(i = 0; i < rown; i++) {
for(j = 0; j < coln; j++){
if(visited[i][j] == 0&& G[i][j] == 0) {
count++;
bfs(G,i, j, rown, coln);
}
}
}
return count;
}
No comments:
Post a Comment