Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 완전탐색
- 위상정렬
- Effective Java
- 동적계획법
- 이분탐색
- 플로이드-와샬
- BFS
- java
- 투 포인터
- dfs
- 세그먼트 트리
- swea
- 백준
- mst
- Network
- Kotlin
- 유니온 파인드
- 스택
- 에라토스테네스의 체
- 프로그래머스
- CS
- JUnit 5
- 백트래킹
- 그리디
- 수학
- 구현
- 알고리즘
- 시뮬레이션
- 후니의 쉽게 쓴 시스코 네트워킹
- 문자열
Archives
반갑습니다!
[백준] 1600 말이 되고픈 원숭이 본문
못가는 경우가 없는줄 알고 풀었다가 1번 틀렸다.. 문제를 꼼꼼히 읽자..
풀이
정말 조금 변형된 BFS이다. 4방향 탐색과 말처럼 이동할 수 있는 8방향 탐색을 해주면 된다.
코드
#include <iostream>
#include <queue>
using namespace std;
struct monkey {
int x, y, cnt, k_cnt;
};
int k, w, h;
int map[201][201];
bool visited[201][201][31];
const int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
const int h_dx[] = { 1, 2, 2, 1, -1, -2, -2, -1 }, h_dy[] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int bfs() {
queue<monkey> q;
q.push({ 1, 1, 0, 0});
visited[1][1][0] = true;
while (!q.empty()) {
int x = q.front().x;
int y = q.front().y;
int cnt = q.front().cnt;
int k_cnt = q.front().k_cnt;
if (x == w && y == h) return cnt;
q.pop();
// 인접한 4방향 탐색
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 1 || nx > w || ny < 1 || ny > h || map[ny][nx] == true || visited[ny][nx][k_cnt] == true) continue;
visited[ny][nx][k_cnt] = true;
q.push({ nx, ny, cnt + 1, k_cnt });
}
// k번만큼 다 이동한 경우에는 인접한 4방향으로만 이동
if (k_cnt == k) continue;
// 말처럼 이동할 수 있는지 탐색
for (int i = 0; i < 8; i++) {
int nx = x + h_dx[i];
int ny = y + h_dy[i];
if (nx < 1 || nx > w || ny < 1 || ny > h || map[ny][nx] == true || visited[ny][nx][k_cnt+1] == true) continue;
visited[ny][nx][k_cnt+1] = true;
q.push({ nx, ny, cnt + 1, k_cnt + 1 });
}
}
return -1;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> k;
cin >> w >> h;
for (int i = 1; i <= h; i++)
for (int j = 1; j <= w; j++)
cin >> map[i][j];
cout << bfs() << '\n';
return 0;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 5052 전화번호 목록 (0) | 2020.04.23 |
---|---|
[백준] 2234 성곽 (0) | 2020.04.22 |
[백준] 1726 로봇 (0) | 2020.04.22 |
[백준] 1063 킹 (0) | 2020.04.22 |
[SWEA] 1486 장훈이의 높은 선반 (0) | 2020.04.21 |