본문 바로가기

Algorithm/BAEKJOON

[BOJ] 2665번 미로 만들기 (C++)

728x90
반응형

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

 

2665번: 미로만들기

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

www.acmicpc.net

 

#include <iostream>
#include <string>
#include <queue>
using namespace std;

int n;
int arr[50][50];
int visited[50][50];

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

void bfs(){
	queue<pair<int, pair<int, int>>> q;
	q.push({0, {0, 0}});
	
	while(!q.empty()){
		int cnt = q.front().first;
		int cx = q.front().second.first;
		int cy = q.front().second.second;
		q.pop();
		
		for(int i = 0; i < 4; i++){
			int nx = cx + dx[i];
			int ny = cy + dy[i];
			
			if(!(nx >= 0 && ny >= 0 && nx < n && ny < n)) continue;
			
			if(visited[nx][ny] > cnt){
				if(arr[nx][ny] == 0){
					q.push({cnt + 1, {nx, ny}});
					visited[nx][ny] = cnt + 1;
				} else{
					q.push({cnt, {nx, ny}});
					visited[nx][ny] = cnt;
				}
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	cin >> n;
	string str;
	for(int i = 0; i < n; i++){
		cin >> str;
		for(int j = 0; j < n; j++){
			arr[i][j] = str[j] - '0';
			visited[i][j] = 987654321;
		}
	}
	bfs();
	cout << visited[n - 1][n - 1] << endl;
	return 0;
}

 

큐에 들어간 원소는 {cnt, {x, y}}이다. 이 때 cnt는 현재까지 검은 방을 흰 방으로 바꾼 횟수이다.

visited[x][y]는 x, y에 도착하기 위해서 든 최소 cnt 값이다.

 

 

visited에 최소 횟수를 담기 위해 987654321로 초기화 시켜준다.

 

cnt를 이용해 다음 칸에 갈지 말지 판단한다. cnt가 다음 칸을 도착하기 위한 색을 바꾼 최소 횟수(visited[nx][ny])보다 작다면 최소한으로 이동할 수 있는 방법이므로 방문한다.

 

다음 이동할 방이 검은 방인 경우 흰 방으로 변경해야 하므로 현재 cnt에서 1을 더해 큐에 넣어준다.

흰 방인 경우 현재 cnt를 그대로 가져가면 된다.

728x90
반응형

'Algorithm > BAEKJOON' 카테고리의 다른 글

[BOJ] 2573번 빙산 (C++)  (0) 2022.08.17
[BOJ] 13904번 과제 (C++)  (0) 2022.08.16
[BOJ] 16927번 배열 돌리기 2 (C++)  (0) 2022.08.12
[BOJ] 16926번 배열 돌리기 (C++)  (0) 2022.08.11
[BOJ] 7569번 토마토 (C++)  (0) 2022.08.11