๋ฌธ์ :
๋ถ์ :
์ด ๋ฌธ์ ๋ BFS๋ก ํ์๋ค.(DFS๋ก ํ์ด๋ ๋ ธ์๊ด)
์ ํ์ ์ธ BFS ๋ฌธ์ ์ด์ง๋ง ๋์ด์ง ๋ฐฉ๋ฌธ ์์น๊ฐ ์๊ธฐ ๋๋ฌธ์ ์ข ๋ง๋ถ์์ ๋ณด์๋ ๊ฒ์ฒ๋ผ BFS_ALL์ ํด์ฃผ์ด์ผ ํ๋ค.
c++ ์ฝ๋ :
//
// 2667_complex.cpp
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2021/02/14.
//
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 100
int n;
int find_one = 0;
int cnt = 0;
bool visit[MAX][MAX];
bool map [MAX][MAX];
int dx[] = { 0, 0, 1, -1 }; //up down left right
int dy[] = { 1, -1, 0, 0 };
int dfs(pair<int, int> start){
int count = 1;
visit[start.first][start.second] = true;
stack<pair<int, int>> s;
s.push(make_pair(start.first, start.second));
while(!s.empty()){//stack s๊ฐ ๋น์ด ์์ง ์์ ๋์
int x = s.top().first;
int y = s.top().second;
//cout << y << " " << x << endl;
s.pop();
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && ny >= 0 && nx < n && ny < n){
if(visit[nx][ny] == false && map[nx][ny]){ // ๋ฐฉ๋ฌธํ์ง ์์๊ณ ๊ฐ ์ ์๋ ๊ธธ์ด๋ผ๋ฉด
visit[nx][ny] = true; // ๋ฐฉ๋ฌธํ ๊ฒ์ ํ๋ณ
count++;
s.push(make_pair(nx, ny));
}
}
}
}
return count;
}
void dfsAll(){
vector<int> ans;
memset(visit, false, sizeof(visit));
pair<int, int> start;
for(int i =0; i < n; i++){
for(int j = 0; j < n; j++){
if(map[i][j] == true && visit[i][j] == false){ // ์์ง ๊ฐ์ง ์์์ง๋ง 1์ธ๊ฒ ๋จ์ ์๋ ๊ฒฝ์ฐ
start = make_pair(i, j);
int cnt = dfs(start);
//cout << cnt << endl;
ans.push_back(cnt);
}
}
}
sort(ans.begin(), ans.end());
cout << (int)ans.size() << endl;
for(int i = 0; i < (int)ans.size(); i++){
cout << ans.at(i) << endl;
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
int a;
scanf("%1d", &a);
if(a == 1){
map[i][j] = true;
}else{
map[i][j] = false;
}
}
}
// for(int i = 0; i < n; i++){
// for(int j = 0; j < n; j++){
//
// cout << map[i][j] << " ";
// }
// cout << endl;
// }
dfsAll();
return 0;
}
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2617 ๊ตฌ์ฌ ์ฐพ๊ธฐ DFS (0) | 2021.02.26 |
---|---|
[๋ฐฑ์ค] 2003 ์๋ค์ ํฉ2 ํฌ ํฌ์ธํฐ (2) | 2021.02.26 |
[๋ฐฑ์ค] 18870 ์ขํ ์์ถ (0) | 2021.02.19 |
[๋ฐฑ์ค] 2660 ํ์ฅ ๋ฝ๊ธฐ Floyd Warshall (0) | 2021.02.18 |
[๋ฐฑ์ค] 11403 ๊ฒฝ๋ก ์ฐพ๊ธฐ Floyd Warshall (0) | 2021.02.18 |
๋๊ธ