반응형
https://www.acmicpc.net/problem/5558
5558번: チーズ (Cheese)
入力は H+1 行ある.1 行目には 3 つの整数 H,W,N (1 ≦ H ≦ 1000,1 ≦ W ≦ 1000,1 ≦ N ≦ 9) がこの順に空白で区切られて書かれている.2 行目から H+1 行目までの各行には,'S','1', '2', ..., '9',
www.acmicpc.net
[ 문제풀이 ]
1. 지도를 입력받고, S의 위치를 queue에 넣습니다.
2. visited [ 1001 ][ 1001 ][ 10 ] 배열을 만들어 먹은 치즈와 방문 여부를 저장합니다.
3. bfs를 이용하여 먹은 치즈가 K일 경우 현재까지 이동한 거리인 cnt를 출력합니다.
[ 소스코드 ]
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 | #include<iostream> #include<queue> using namespace std; int H, W, N; char arr[1001][1001]; int visited[1001][1001][10]; int dy[4] = { -1,1,0,0 }; int dx[4] = { 0,0,-1,1 }; struct pos { int y; int x; int cheese; int cnt; }; int main() { queue<pos> q; scanf("%d %d %d", &H, &W, &N); for (int i = 0; i < H; i++) { scanf("%s", arr[i]); } for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (arr[i][j] == 'S') { q.push({ i,j,0,0 }); visited[i][j][0] = 1; break; } } if (!q.empty()) break; } while (!q.empty()) { const int y = q.front().y; const int x = q.front().x; const int cheese = q.front().cheese; const int cnt = q.front().cnt; q.pop(); if (cheese == N) { printf("%d", cnt); return 0; } for (int i = 0; i < 4; i++) { const int yy = y + dy[i]; const int xx = x + dx[i]; if (yy >= 0 && yy < H && xx >= 0 && xx < W) { if (arr[yy][xx] != 'X') { if (arr[yy][xx] == cheese + '0' + 1) { if (visited[yy][xx][cheese + 1] != 1) { visited[yy][xx][cheese + 1] = 1; q.push({ yy,xx,cheese + 1,cnt + 1 }); } } else { if (visited[yy][xx][cheese] != 1) { visited[yy][xx][cheese] = 1; q.push({ yy,xx,cheese,cnt + 1 }); } } } } } } } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 17090번 - 미로 탈출하기 (C++) (0) | 2023.01.27 |
---|---|
[ 백준 ] 14923번 - 미로 탈출 (C++) (0) | 2023.01.26 |
[ 백준 ] 3770번 - 대한민국 (C++) (0) | 2023.01.24 |
[ 백준 ] 9463번 - 순열 그래프 (C++) (0) | 2023.01.23 |
[ 백준 ] 10090번 - Counting Inversions (C++) (0) | 2023.01.22 |