반응형

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

 

 

[ 문제풀이 ]

 

1. visited 배열을 만들어 각각 목적지에 방문 여부를 저장합니다.

 

2. node struct를 만들어 y, x 좌표와 cnt를 저장합니다.

 

3. bfs를 돌면서 가장 일찍 도착한 시간을 visited 배열에 갱신합니다.

 

4. visited 배열을 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
 
using namespace std;
 
int n, m;
int arr[1000][1000];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
int visited[1000][1000];
int y, x;
 
struct node {
    int y;
    int x;
    int cnt;
};
 
int main()
{
    scanf("%d %d"&n, &m);
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            visited[i][j] = 987654321;
            scanf("%d"&arr[i][j]);
            if (arr[i][j] == 2) {
                y = i;
                x = j;
            }
        }
    }
 
    queue<node> q;
 
    q.push({ y,x,0 });
 
    while (!q.empty()) {
        const int y = q.front().y;
        const int x = q.front().x;
        const int cnt = q.front().cnt;
        q.pop();
 
        if (visited[y][x] < cnt) continue;
        visited[y][x] = cnt;
 
        for (int i = 0; i < 4; i++) {
            int yy = y + dy[i];
            int xx = x + dx[i];
 
            if (yy >= 0 && yy < n && xx >= 0 && xx < m && arr[yy][xx] != 0) {
                if (visited[yy][xx] > cnt + 1) {
                    visited[yy][xx] = cnt + 1;
                    q.push({ yy,xx,cnt + 1 });
                }
            }
        }
    }
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 0) {
                printf("0 ");
            }
            else {
                if (visited[i][j] != 987654321) {
                    printf("%d ", visited[i][j]);
                }
                else {
                    printf("-1 ");
                }
            }
        }
        printf("\n");
    }
}
cs
반응형

+ Recent posts