-
[14940] 쉬운 최단거리BOJ 2021. 11. 9. 13:54
https://www.acmicpc.net/problem/14940
14940번: 쉬운 최단거리
지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000) 다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이
www.acmicpc.net
<문제>
'2'를 시작점으로 전부 bfs를 돌려주고, -1로 초기화된 dist[][]에 최단경로를 저장해두었다가 출력할때
'1'에 대해서 거리를 출력, 그 외에는 0을 출력하면 된다.
<소스코드>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849#include <bits/stdc++.h>using namespace std;int n, m, dy[4] = {0, 1, 0, -1}, dx[4] = {1, 0, -1, 0}, dist[1001][1001],a[1001][1001];typedef struct {int y, x;} state;void bfs(int sy, int sx) {memset(dist, -1, sizeof(dist));dist[sy][sx] = 0;queue<state> q;q.push({sy, sx});while (!q.empty()) {auto cur = q.front();q.pop();for (int i = 0; i < 4; i++) {int y = cur.y + dy[i];int x = cur.x + dx[i];if (y < 0 || x < 0 || y >= n || x >= m) continue;if (a[y][x] == 1 && dist[y][x] == -1) {dist[y][x] = dist[cur.y][cur.x] + 1;q.push({y, x});}}}}int main(void) {int i, j, sy, sx;cin >> n >> m;for (i = 0; i < n; i++)for (j = 0; j < m; j++) {cin >> a[i][j];if (a[i][j] == 2) {sy = i;sx = j;}}bfs(sy, sx);for (i = 0; i < n; i++) {for (j = 0; j < m; j++) {if (a[i][j] == 1)cout << dist[i][j] << " ";elsecout << "0 ";}cout << '\n';}return 0;}cs 'BOJ' 카테고리의 다른 글
[14395] 4연산 (0) 2021.11.09 [16973] 직사각형 탈출 (0) 2021.11.09 [15971] 두 로봇 (0) 2021.11.09 [17836] 공주님을 구해라! (0) 2021.11.09 [2194] 유닛 이동시키기 (0) 2021.11.08