algorithm'''problem solve
[백준] 2667 - 단지번호붙이기(설명X)
JunHwa Park
2020. 5. 9. 17:11
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 | #include <cstdio> #include <queue> using namespace std; int bfs(int** arr, int** visited, int size, int x, int y) { queue<pair<int, int>> order; order.push({ x, y }); int num = 0; visited[x][y] = 1; while (!order.empty()) { pair<int, int> now = order.front(); order.pop(); num++; if (now.first + 1 < size && arr[now.first + 1][now.second] == 1 && visited[now.first + 1][now.second] == 0) { order.push({ now.first + 1, now.second }); visited[now.first + 1][now.second] = 1; } if (now.first - 1 >= 0 && arr[now.first - 1][now.second] == 1 && visited[now.first - 1][now.second] == 0) { order.push({ now.first - 1, now.second }); visited[now.first - 1][now.second] = 1; } if (now.second + 1 < size && arr[now.first][now.second + 1] == 1 && visited[now.first][now.second + 1] == 0) { order.push({ now.first, now.second + 1 }); visited[now.first][now.second + 1] = 1; } if (now.second - 1 >= 0 && arr[now.first][now.second - 1] == 1 && visited[now.first][now.second - 1] == 0) { order.push({ now.first, now.second - 1 }); visited[now.first][now.second - 1] = 1; } } return num; } int main() { int N; scanf("%d", &N); priority_queue<int, vector<int>, greater<int>> pqueue; int** arr = new int* [N]; for (int i = 0; i < N; i++) { arr[i] = new int[N]; for (int j = 0; j < N; j++) scanf("%1d", &arr[i][j]); } int** visited = new int* [N]; for (int i = 0; i < N; i++) visited[i] = new int[N] {0, }; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[i][j] == 1 && visited[i][j] == 0) pqueue.push(bfs(arr, visited, N, i, j)); } } printf("%d\n", pqueue.size()); while (!pqueue.empty()) { printf("%d\n", pqueue.top()); pqueue.pop(); } } | cs |