반응형

11607번: Grid
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains two space-separated integers n and m (1≤n,m≤500), indicating the size of the grid. It is guaranteed th
www.acmicpc.net
그래프문제 조아
#include<iostream> #include<queue> #include<string> using namespace std; int n, m; int map[500][500]; bool visit[500][500]; int result[500][500]; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; queue<pair<int, int>> q; void bfs() { while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for(int i = 0; i < 4; i++) { // 각 칸마다 칸에 써져있는 수 만큼 이동할 수 있으므로 칸의 수만큼 곱해준다. int nx = x + (dx[i] * map[x][y]); int ny = y + (dy[i] * map[x][y]); if(nx >= 0 && nx < n && ny >= 0 && ny < m) { if(visit[nx][ny] == false) { q.push({nx, ny}); visit[nx][ny] = true; result[nx][ny] = result[x][y] + 1; // 이동거리 수를 구해야 하므로 1씩 더해줌 } } } } } int main() { scanf("%d %d", &n, &m); for(int x = 0; x < n; x++) { string temp; cin >> temp; for(int y = 0; y < m; y++) { map[x][y] = temp[y] - '0'; } } q.push({0, 0}); visit[0][0] = true; bfs(); if(result[n-1][m-1] == 0) { // 만약 도달하지 못했다면 printf("IMPOSSIBLE\n"); } else { // 아니라면 시작지점부터 끝지점까지의 이동횟수의 최솟값을 출력 printf("%d\n", result[n-1][m-1]); } return 0; }
반응형
'BaekJoon > C++' 카테고리의 다른 글
3055 : 탈출 (C++) (0) | 2021.03.03 |
---|---|
14940 : 쉬운 최단거리 (C++) (0) | 2021.03.02 |
11370 : Spawn of Ungoliant (C++) (0) | 2021.02.27 |
5378 : Hex (C++) (0) | 2021.02.27 |
6764 : Sounds fishy! (C++) (0) | 2021.02.26 |
댓글