Study hard

(c++)백준 1600번: 말이 되고픈 원숭이 본문

백준/bfs, dfs

(c++)백준 1600번: 말이 되고픈 원숭이

Nimgnoej 2021. 2. 12. 09:19

www.acmicpc.net/problem/1600

 

1600번: 말이 되고픈 원숭이

첫째 줄에 정수 K가 주어진다. 둘째 줄에 격자판의 가로길이 W, 세로길이 H가 주어진다. 그 다음 H줄에 걸쳐 W개의 숫자가 주어지는데, 0은 아무것도 없는 평지, 1은 장애물을 뜻한다. 장애물이 있

www.acmicpc.net

[풀이]

bfs를 사용하여 풀었다.

말처럼 이동한 횟수가 K번 미만이면 말처럼 이동한 칸을 queue에 넣는다. 그리고 원숭이로 이동하는 경우 또한 queue에 넣어야한다.

 

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

struct Monkey {
	int x, y;
	int horse;//말 방식으로 이동한 횟수
	int dist;//해당 칸까지 이동한 횟수
};

int K, W, H;
int Map[200][200];
bool visited[200][200][31];
const int dhorse[][2] = { {-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2} };
const int dmonkey[][2] = { {-1,0},{1,0},{0,-1},{0,1} };

int bfs() {
	queue<Monkey>q;
	q.push({ 0,0,0,0 });
	visited[0][0][0] = true;
	while (!q.empty()) {
		int x = q.front().x;
		int y = q.front().y;
		int horse = q.front().horse;
		int dist = q.front().dist;
		q.pop();
		if (x == H - 1 && y == W - 1) {
			return dist;
		}
		//말의 움직임으로 움직이는 경우
		if (horse < K) {
			for (int i = 0; i < 8; i++) {
				int nx = x + dhorse[i][0];
				int ny = y + dhorse[i][1];
				if (nx < 0 || nx >= H || ny < 0 || ny >= W)
					continue;
				if (Map[nx][ny] == 0 && visited[nx][ny][horse + 1] == false) {
					visited[nx][ny][horse + 1] = true;
					q.push({ nx,ny,horse + 1,dist + 1 });
				}
			}
		}
		//원숭이의 움직임으로 움직이는 경우
		for (int i = 0; i < 4; i++) {
			int nx = x + dmonkey[i][0];
			int ny = y + dmonkey[i][1];
			if (nx < 0 || nx >= H || ny < 0 || ny >= W)
				continue;
			if (Map[nx][ny] == 0 && visited[nx][ny][horse] == false) {
				visited[nx][ny][horse] = true;
				q.push({ nx,ny,horse,dist + 1 });
			}
		}
	}
	return -1;
}

int main() {
	cin >> K >> W >> H;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> Map[i][j];
		}
	}
	int res = bfs();
	cout << res << '\n';
	return 0;
}

'백준 > bfs, dfs' 카테고리의 다른 글

(c++)백준 2234번: 성곽  (0) 2021.02.16
(c++)백준 17141번: 연구소 2  (0) 2021.02.14
(c++)백준 16946번: 벽 부수고 이동하기 4  (0) 2021.02.07
(c++)백준 16236번: 아기 상어  (0) 2020.10.17
(c++)백준 17142번: 연구소 3  (0) 2020.10.17