백준 알고리즘 2665번 : 미로 만들기

Zoo Da·2021년 8월 8일
0

백준 알고리즘

목록 보기
150/337
post-thumbnail

링크

문제

n×n 바둑판 모양으로 총 n2개의 방이 있다. 일부분은 검은 방이고 나머지는 모두 흰 방이다. 검은 방은 사면이 벽으로 싸여 있어 들어갈 수 없다. 서로 붙어 있는 두 개의 흰 방 사이에는 문이 있어서 지나다닐 수 있다. 윗줄 맨 왼쪽 방은 시작방으로서 항상 흰 방이고, 아랫줄 맨 오른쪽 방은 끝방으로서 역시 흰 방이다.

시작방에서 출발하여 길을 찾아서 끝방으로 가는 것이 목적인데, 아래 그림의 경우에는 시작방에서 끝 방으로 갈 수가 없다. 부득이 검은 방 몇 개를 흰 방으로 바꾸어야 하는데 되도록 적은 수의 방의 색을 바꾸고 싶다.

아래 그림은 n=8인 경우의 한 예이다.

위 그림에서는 두 개의 검은 방(예를 들어 (4,4)의 방과 (7,8)의 방)을 흰 방으로 바꾸면, 시작방에서 끝방으로 갈 수 있지만, 어느 검은 방 하나만을 흰 방으로 바꾸어서는 불가능하다. 검은 방에서 흰 방으로 바꾸어야 할 최소의 수를 구하는 프로그램을 작성하시오.

단, 검은 방을 하나도 흰방으로 바꾸지 않아도 되는 경우는 0이 답이다.

입력

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

출력

첫 줄에 흰 방으로 바꾸어야 할 최소의 검은 방의 수를 출력한다.

예제 입력 및 출력

풀이법

알고스팟과 동일한 문제 풀이이다...

풀이 코드(C++)

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<list>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
#include<tuple>
#include<functional>
#include<utility>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<complex>
#include<cassert>
#define X first
#define Y second
#define pb push_back
#define MAX 51
#define INF 1e9
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;

int n;
int dist[MAX][MAX];
int adj[MAX][MAX];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};

void dijkstra(){
  priority_queue<pair<int,pair<int,int>>,vector<pair<int, pair<int,int>>>,greater<pair<int,pair<int,int>>>> pq;
  // <비용,<x좌표,y좌표>순 구성
  dist[1][1] = adj[1][1];
  pq.push({dist[1][1],{1,1}});

  while(!pq.empty()){
    int weight = pq.top().first;
    int curX = pq.top().second.first;
    int curY = pq.top().second.second;
    pq.pop();

    if(dist[curX][curY] < weight) continue;
    for(int i = 0; i < 4; i++){
      int xx = curX + dx[i];
      int yy = curY + dy[i];
      int nWeight = weight + adj[xx][yy];
      if(xx < 1 || xx > n || yy < 1 || yy > n) continue;
      if(dist[xx][yy] > nWeight){
        dist[xx][yy] = nWeight;
        pq.push({nWeight,{xx, yy}});
      }
    }
  }
}


int main(){
  cin >> n;
  for(int i = 1; i <= n; i++){
    for(int j = 1; j <= n; j++){
      dist[i][j] = INF;
    }
  }
  for(int i = 1; i <= n; i++){
    for(int j = 1; j <= n; j++){
      scanf("%1d",&adj[i][j]);
      adj[i][j] = adj[i][j]==1 ? 0 : 1;
    }
  }
  dijkstra();
  cout << dist[n][n];
  return 0;
}

profile
메모장 겸 블로그

0개의 댓글