[BOJ][실1][2178] 미로 탐색

문제 링크

문제링크

첫 번째 풀이 : BFS

알고리즘

가장 기본적인 BFS를 진행합니다. 그리고 dp를 사용합니다.

  • dp[x][y] : 현재까지 오는데 걸린 칸의 수
  • dp[nx][ny] = dp[x][y]+1

정답 코드

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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, m;
int arr[101][101];
int dp[101][101];
bool visited[101][101];

typedef pair<int, int> pii;

int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };

void bfs(int x, int y) {
  queue<pii> q;
  int nx, ny = 0;
  visited[x][y] = true;
  q.push(make_pair(x, y));
  while (!q.empty()) {
    pii curr = q.front(); 
    q.pop();
    for (int k = 0; k < 4; k++) {
      nx = curr.first + dx[k];
      ny = curr.second + dy[k];
      if (nx < 0 || nx >= n) continue;
      if (ny < 0 || ny >= m) continue;
      if (arr[nx][ny] == 1 && !visited[nx][ny]) {
        visited[nx][ny] = true;
        dp[nx][ny] = dp[curr.first][curr.second] + 1;
        q.push(make_pair(nx, ny));
      }
    }
  }
}

void show(void) {
  cout << "============show========\n";
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cout << dp[i][j];
    }
    cout << "\n";
  }
  cout << "========================\n";
}

int main()
{
  //freopen("input.txt", "r", stdin);
  //ios_base::sync_with_stdio(0); cin.tie(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%1d", &arr[i][j]);
    }
  }

  bfs(0, 0);
  cout << dp[n - 1][m - 1] + 1;
  return 0;
}

Success Notice: 수고하셨습니다. :+1:

Leave a comment