알고리즘 문제/BOJ
16920번 확장 게임
parkit
2020. 3. 10. 16:10
728x90
반응형
https://www.acmicpc.net/problem/16920
1부터 숫자들의 위치를 저장하고, bfs를 갈 수 있는 거리만큼 실행한다.
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 | #include <bits/stdc++.h> using namespace std; #define Max 1010 int n, m, p, path[Max], answer[Max]; int dy[4] = { 0, 1, 0, -1 }; int dx[4] = { 1, 0, -1, 0 }; char Map[Max][Max]; bool visit[Max][Max]; queue<pair<int, int> > q[Max]; void bfs() { while (1) { bool stop = true; // 1부터 차례대로 for (int num = 1; num <= p; num++) { // 얼마만큼 가는지 int len = path[num]; // 비어있지 않고, 길이만큼만 간다 while (!q[num].empty() && len--) { int qs = q[num].size(); while (qs--) { int r = q[num].front().first; int c = q[num].front().second; q[num].pop(); for (int i = 0; i < 4; i++) { int y = r + dy[i]; int x = c + dx[i]; if (y < 0 || y >= n || x < 0 || x >= m || visit[y][x] || Map[y][x] != '.') { continue; } stop = false; ++answer[num]; // 계산 visit[y][x] = true; q[num].push({ y, x }); } } } } // 더 이상 진행하지 않아도 되면, 탈출 if (stop) { break; } } } int main() { cin.tie(0); scanf("%d %d %d", &n, &m, &p); for (int i = 1; i <= p; i++) { scanf("%d", &path[i]); } for (int i = 0; i < n; i++) { scanf("%s", &Map[i][0]); for (int j = 0; j < m; j++) { if (Map[i][j] != '.' && Map[i][j] != '#') { q[Map[i][j] - '0'].push({ i, j }); visit[i][j] = true; ++answer[Map[i][j] - '0']; } } } bfs(); for (int i = 1; i <= p; i++) { printf("%d ", answer[i]); } printf("\n"); return 0; } | cs |
728x90
반응형