반응형

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

매우 기본적인 bfs문제입니다. 방향 배열을 통해서 인접한 4방향으로 이동하고, visited배열을 통해서 방문을 체크해주면 됩니다. 지도에서 값이 1인 길일 때만 queue에 push 해주고, 방문을 한 번이라도 했다면 그 좌표는 무시해줍니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
 
using namespace std;
 
struct node {
    int y;
    int x;
    int cnt;
};
 
int N, M;
char arr[100][101];
int visited[100][100];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
int main()
{
    scanf("%d %d"&N, &M);
 
    for (int i = 0; i < N; i++) {
        scanf("%s", arr[i]);
    }
 
    queue<node> q;
    q.push({ 0,0,1 });
 
    while (!q.empty())
    {
        int y = q.front().y;
        int x = q.front().x;
        int cnt = q.front().cnt;
        q.pop();
 
        if (y == N - 1 && x == M - 1) {
            printf("%d", cnt);
            return 0;
        }
 
        if (visited[y][x]) continue;
        visited[y][x] = 1;
 
        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) {
                if (arr[yy][xx] == '1' && visited[yy][xx] != 1) {
                    q.push({ yy,xx,cnt + 1 });
                }
            }
        }
    }
}
cs
반응형

+ Recent posts