※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 6129번 문제인 Obstacle Course이다.
문제는 아래 링크를 확인하자.

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

 

6129번: Obstacle Course

The cow must make at least 2 turns: For example, the cow may start by facing south, move south, turn to face west, move west, move west, then turn to face south, and finally move south into the B square.

www.acmicpc.net

주어진 2차원 배열에서 출발점에서 도착점까지 도달하기 위한 최소 회전횟수를 묻는 문제이다.

 

이 경우 "회전횟수"를 거리로 취급하여 BFS를 진행하면 최단거리, 즉 최소 회전횟수를 구할 수 있으므로 이를 이용해 문제를 해결할 수 있다.

 

아래는 제출한 소스코드이다.

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

int N;
int sR, sC, eR, eC;
string board[102];
int dist[102][102];

void bfs() {
	queue<pair<int, int>> que;
	que.push(make_pair(sR, sC));
	dist[sR][sC] = 1;
	
	while (!que.empty()) {
		int r = que.front().first, c = que.front().second; que.pop();
		for (int rr = r + 1; board[rr][c] != 'x'; rr++) {
			if (dist[rr][c]) continue;
			dist[rr][c] = dist[r][c] + 1;
			que.push(make_pair(rr, c));
		}
		for (int rr = r - 1; board[rr][c] != 'x'; rr--) {
			if (dist[rr][c]) continue;
			dist[rr][c] = dist[r][c] + 1;
			que.push(make_pair(rr, c));
		}
		for (int cc = c + 1; board[r][cc] != 'x'; cc++) {
			if (dist[r][cc]) continue;
			dist[r][cc] = dist[r][c] + 1;
			que.push(make_pair(r, cc));
		}
		for (int cc = c - 1; board[r][cc] != 'x'; cc--) {
			if (dist[r][cc]) continue;
			dist[r][cc] = dist[r][c] + 1;
			que.push(make_pair(r, cc));
		}
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> N;
	for (int c = 0; c <= N; c++) board[0] += 'x';
	for (int r = 1; r <= N; r++) {
		cin >> board[r];
		board[r] = "x" + board[r] + "x";
	}
	for (int c = 0; c <= N; c++) board[N + 1] += 'x';

	for (int r = 1; r <= N; r++) {
		for (int c = 1; c <= N; c++) {
			if (board[r][c] == 'A') sR = r, sC = c;
			else if (board[r][c] == 'B') eR = r, eC = c;
		}
	}

	bfs();

	cout << dist[eR][eC] - 2;
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 6131 // C++] 완전 제곱수  (0) 2022.09.13
[BOJ 6130 // C++] Privileged Cows  (0) 2022.09.12
[BOJ 6128 // C++] Bessie's Secret Pasture  (0) 2022.09.10
[BOJ 6127 // C++] Super Paintball  (0) 2022.09.09
[BOJ 6126 // C++] Cow Cash  (0) 2022.09.08

+ Recent posts