백준의 단지번호붙이기(2667) 문제입니다.
( www.acmicpc.net/problem/2667 )
[ 문제설명 ]
- 정사각형의 한 변의 길이를 입력받고, 맵을 입력받습니다.
- 맵은 1과 0으로 이루어져 있으며, 0은 집이 없는 곳을 1은 집이 있는 곳을 의미합니다.
- 서로 연결되어 있는(상하좌우 중 한 방향으로라도 붙어 있으면) 집들을 단지 라고 부릅니다.
- 총 몇개의 단지가 있는지 구하고, 그 단지에 있는 집의 수를 오름차순으로 출력시키면 됩니다.
[ 풀이과정 ]
1) 맵을 입력받는 과정에서, 집이 있는 곳(1) 을 입력 받을 때, 벡터에 넣어줍니다.
2) 벡터에 넣은 위치에서부터 BFS를 돌려주면 됩니다.
3) BFS를 돌리면서, BFS를 돈 횟수를 Count해줄 변수를 설정해주고,
BFS안에서 몇 번 실행되는지(이웃한 집의 갯수 Count)를 Count해줄 변수를 설정해서 Count 해주고,
그 값을 벡터에 넣어줍니다.
4) BFS를 돈 횟수를 Count해준 변수를 출력시키고(단지의 갯수) 벡터에 넣어준 집의 갯수들을
오름차순으로 정렬 후 출력시켜 주면 됩니다.
[ 소스코드 ]
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | #include<iostream> #include<algorithm> #include<queue> #include<string> #include<vector> #define endl "\n" #define MAX 25 using namespace std; int N, Area_Num; int MAP[MAX][MAX]; bool Visit[MAX][MAX]; int dx[] = { 0, 0, 1, -1 }; int dy[] = { 1, -1, 0, 0 }; vector<pair<int, int>> V; vector<int> Area_Cnt; void Input() { Area_Num = 0; cin >> N; for (int i = 0; i < N; i++) { string Inp; cin >> Inp; for (int j = 0; j < Inp.length(); j++) { int Temp = Inp[j] - '0'; MAP[i][j] = Temp; if (MAP[i][j] == 1) V.push_back(make_pair(i, j)); } } } void BFS(int a, int b) { queue<pair<int,int>> Q; Q.push(make_pair(a, b)); Visit[a][b] = true; int Cnt = 1; while (Q.empty() == 0) { int x = Q.front().first; int y = Q.front().second; Q.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] == 1) { Visit[nx][ny] = true; Q.push(make_pair(nx, ny)); Cnt++; } } } } Area_Num++; Area_Cnt.push_back(Cnt); } void Solution() { for (int i = 0; i < V.size(); i++) { int x = V[i].first; int y = V[i].second; if (Visit[x][y] == 0) BFS(x, y); } sort(Area_Cnt.begin(), Area_Cnt.end()); cout << Area_Num << endl; for (int i = 0; i < Area_Num; i++) { cout << Area_Cnt[i] << endl; } } void Solve() { Input(); Solution(); } int main(void) { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); //freopen("Input.txt", "r", stdin); Solve(); return 0; } | cs |
'[ BOJ Code ] > # BOJ -' 카테고리의 다른 글
[ 백준 1003 ] 피보나치 함수 (C++) (0) | 2018.11.28 |
---|---|
[ 백준 7576 ] 토마토 (C++) (2) | 2018.11.28 |
[ 백준 1697 ] 숨바꼭질 (C++) (0) | 2018.11.28 |
[ 백준 1260 ] DFS와 BFS (C++) (0) | 2018.11.28 |
[ 백준 1012 ] 유기농배추 (C++) (2) | 2018.11.28 |