Compy's Blog
361 words
2 minutes
[BOJ] 다리 만들기
2025-02-23

다리 만들기

TimeLimitMemoryLimitConditionTAG
2s192MB1 ≤ N ≤ 100BFS

전형적인 BFS 문제로 그냥 열심히 돌리면 정답이 나오는 문제입니다.

조금 신경써야 할 것은 visit 처리를 기본적으로 해주면 쉽게 풀립니다.

정답 코드
#include <iostream>
#include <queue>
using namespace std;

using ll = long long;

int n;
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int origin[101][101];
int board[101][101];

int solution() {
   int current = 1;
   for(int i = 0; i < n; i++) {
       for(int j = 0; j < n; j++) {
           if(origin[i][j] != 1) continue;
           
           queue<pair<int, int>> q;
           q.push({i, j});
           current++;
           origin[i][j] = current;
           
           while(!q.empty()) {
               auto [y, x] = q.front(); q.pop();
               for(int k = 0; k < 4; k++) {
                   int nx = x + dx[k];
                   int ny = y + dy[k];
                   if(0 <= nx && nx < n && 0 <= ny && ny < n && origin[ny][nx] == 1) {
                       origin[ny][nx] = current;
                       q.push({ny, nx});
                   }
               }
           }
       }
   }

   int result = 1e9;
   for(int start = 2; start <= current; start++) {
       queue<pair<int, int>> q;
       for(int i = 0; i < n; i++) {
           for(int j = 0; j < n; j++) {
               board[i][j] = -1;
               if(origin[i][j] == start) {
                   q.push({i, j});
                   board[i][j] = 0;
               }
           }
       }
       
       while(!q.empty()) {
           auto [y, x] = q.front(); q.pop();
           
           for(int k = 0; k < 4; k++) {
               int nx = x + dx[k];
               int ny = y + dy[k];
               if(0 <= nx && nx < n && 0 <= ny && ny < n) {
                   if(origin[ny][nx] == 0 && board[ny][nx] == -1) {
                       board[ny][nx] = board[y][x] + 1;
                       q.push({ny, nx});
                   }
                   else if(origin[ny][nx] != 0 && origin[ny][nx] != start) {
                       result = min(result, board[y][x]);
                       break;
                   }
               }
           }
       }
   }
   
   return result == 1e9 ? -1 : result;
}

int main() {
   ios_base::sync_with_stdio(false);
   cin.tie(nullptr);
   
   cin >> n;
   for(int i = 0; i < n*n; i++)  cin >> origin[i/n][i%n];
   
   cout << solution();
   return 0;
}
[BOJ] 다리 만들기
https://compy07.github.io/Blog/posts/boj/2146/
Author
뒹굴뒹굴 이정훈 공부방
Published at
2025-02-23