안선생의 개발 블로그

C++ 14940 쉬운 최단거리 본문

백준

C++ 14940 쉬운 최단거리

안선생 2023. 2. 25. 23:07
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
#include <iostream>
#include <vector>
#include<queue>
#include<algorithm>
#include<cstring>
#include<math.h>
using namespace std;
int g[1001][1001= { 0 };
bool visit[1001][1001= { 0 };
int dx[4= { 0,1,-1,0 };
int dy[4= { 1,0,0,-1 };
int n, m, k, l;
bool wc = 0, bc = 0;
bool bfs(int x, int y)
{
    queue <pair<intint>> a;
    a.push({ x,y });
    g[x][y] = 0;
    while (!a.empty())
    {
        int xx = a.front().first;
        int yy = a.front().second;
 
        a.pop();
        for (int i = 0; i < 4; i++)
        {
            int x1 = xx + dx[i];
            int y1 = yy + dy[i];
 
            if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= m || visit[x1][y1]) continue;
 
            if (g[x1][y1])
            {
                a.push({ x1,y1 });
                visit[x1][y1] = 1;
                g[x1][y1] = g[xx][yy] + 1;
            }
        }
    }
 
    return 0;
}
 
int main()
{
    
    cin >> n >> m;
 
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
        {
            cin >> g[i][j];
            if (g[i][j] == 2)
            {
                k = i;
                l = j;
            }
        }
            
 
 
    bfs(k, l);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (!visit[i][j] && g[i][j] >0)
            {
                cout << "-1" << " ";
            }
            else
                cout << g[i][j] << " ";
        }
        cout << "\n";
    }
    return 0;
}
 
cs

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

 

'백준' 카테고리의 다른 글

C++ 1920 수 찾기  (0) 2023.02.27
C++ 5014 스타트링크  (0) 2023.02.26
C++ 13565 침투  (1) 2023.02.25
C++ 1303 전쟁 - 전투  (0) 2023.02.25
C++ 16953 A ->B  (0) 2023.02.25