BOJ 2146: 다리 만들기

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

  • 2월동안 187문제 풀기(지난달 누적 87개) (71/187)
  • 아주 유명한 다리 만들기 문제
  • 생각보다 실수 할 요소가 매우 많다. 정신을 집중하는게 중요함
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
#include <bits/stdc++.h>
using namespace std;

int N;
vector<vector<int>> arr, visit;
struct Coord { int x,y; };

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

inline bool bound(int x) {
  return x >= 0 && x < N;
}

void sweep(int x, int y, queue<Coord>& q, vector<vector<int>>& visit) {
  visit[x][y] = 1;
  q.push({x,y});
  for(int i = 0; i < 4; i++) {
    int nx = x + dx[i];
    int ny = y + dy[i];
    if(!bound(nx) || !bound(ny) || arr[nx][ny] != 1)
      continue;
    arr[nx][ny] = 2;
    sweep(nx,ny,q,visit);
  }
}

int bfs(queue<Coord>& q, vector<vector<int>>& visit) {
  int depth = 0;
  while(int curSize = q.size()) {
    depth++;
    for(int sz = 0; sz < curSize; sz++) {
      Coord cur = q.front(); q.pop();
      for(int i = 0; i < 4; i++) {
        int nx = cur.x + dx[i];
        int ny = cur.y + dy[i];
        if(!bound(nx) || !bound(ny) || visit[nx][ny])
          continue;
        if(arr[nx][ny] != 0)
          return depth-1;
        visit[nx][ny] = 1;
        q.push({nx,ny});
      }
    }
  }
  return -1;
}

void print(vector<vector<int>>& arr) {
  for(int i = 0; i < N; i++) {
    for(int j = 0; j < N; j++)
      printf("%d ", arr[i][j]);
    printf("\n");
  }
}

int main() {
  scanf("%d", &N);
  arr.resize(N, vector<int>(N));
  for(int i = 0; i < N; i++)
    for(int j = 0; j < N; j++)
      scanf("%1d", &arr[i][j]);

  int v = 2;
  int ans = 1e9;
  for(int i = 0; i < N; i++)
    for(int j = 0; j < N; j++)
      if(arr[i][j] == 1) {
        vector<vector<int>> visit(N, vector<int>(N));
        queue<Coord> q;
        sweep(i,j,q,visit);
        ans = min(ans, bfs(q,visit));
      }
  printf("%d", ans);
}