알고리즘 풀이/백준(Boj)
백준(BOJ) 1726번 로봇
100win10
2020. 4. 8. 17:14
문제 : https://www.acmicpc.net/problem/1726
1726번: 로봇
많은 공장에서 로봇이 이용되고 있다. 우리 월드 공장의 로봇은 바라보는 방향으로 궤도를 따라 움직이며, 움직이는 방향은 동, 서, 남, 북 가운데 하나이다. 로봇의 이동을 제어하는 명령어는 다음과 같이 두 가지이다. 명령 1. Go k: k는 1, 2 또는 3일 수 있다. 현재 향하고 있는 방향으로 k칸 만큼 움직인다. 명령 2. Turn dir: dir은 left 또는 right 이며, 각각 왼쪽 또는 오른쪽으로 90° 회전한다. 공장 내 궤도가 설치되
www.acmicpc.net
풀이:
BFS를 통해 처음 부분과 좌표를 넣은 후에 1,2,3만큼 가는 경우와 방향을 바꾸는 경우를 큐에 넣어주어야 한다.
이때 주의할 점은 a [ny][nx]가 1인 부분을 발견했거나 범위를 초과하면 그다음 k는 볼 필요가 없이 바로 break 해주어야 한다.
코드 ( C++ )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <queue> | |
#include <cstring> | |
using namespace std; | |
int a[101][101]; | |
//동서남북 | |
const int dy[4] = { 0,0,1,-1 }; | |
const int dx[4] = { 1,-1,0,0 }; | |
int n, m; | |
int fy, fx, fd; | |
int ey, ex, ed; | |
int dis[101][101][4]; | |
struct g { | |
int y, x, dir; | |
}; | |
int bfs() | |
{ | |
queue<g> q; | |
q.push({ fy,fx,fd }); | |
dis[fy][fx][fd] = 0; | |
while (!q.empty()) { | |
int y = q.front().y; | |
int x = q.front().x; | |
int dir = q.front().dir; | |
q.pop(); | |
if (y == ey && x == ex && dir == ed) { | |
return dis[y][x][dir]; | |
} | |
//현재 방향으로 1,2,3만큼 움직이기 | |
for (int k = 1; k <= 3; ++k) { | |
int ny = y + dy[dir] * k; | |
int nx = x + dx[dir] * k; | |
if (dis[ny][nx][dir] != -1)continue; | |
if (0 <= ny && ny < n && 0 <= nx && nx < m && a[ny][nx] == 0) { | |
dis[ny][nx][dir] = dis[y][x][dir] + 1; | |
q.push({ ny,nx,dir }); | |
} | |
else | |
break; | |
} | |
//방향 바꾸기 | |
if (dir == 0 || dir == 1) { | |
int ndir = 2; | |
if (dis[y][x][ndir] == -1) { | |
dis[y][x][ndir] = dis[y][x][dir] + 1; | |
q.push({ y,x,ndir }); | |
} | |
ndir = 3; | |
if (dis[y][x][ndir] == -1) { | |
dis[y][x][ndir] = dis[y][x][dir] + 1; | |
q.push({ y,x,ndir }); | |
} | |
} | |
if (dir == 2 || dir == 3) { | |
int ndir = 1; | |
if (dis[y][x][ndir] == -1) { | |
dis[y][x][ndir] = dis[y][x][dir] + 1; | |
q.push({ y,x,ndir }); | |
} | |
ndir = 0; | |
if (dis[y][x][ndir] == -1) { | |
dis[y][x][ndir] = dis[y][x][dir] + 1; | |
q.push({ y,x,ndir }); | |
} | |
} | |
} | |
return -1; | |
} | |
int main() { | |
cin >> n >> m; | |
memset(dis, -1, sizeof(dis)); | |
for (int i = 0; i < n; ++i) | |
for (int j = 0; j < m; ++j) { | |
cin >> a[i][j]; | |
} | |
cin >> fy >> fx >> fd; | |
fy -= 1; fx -= 1; fd -= 1; | |
cin >> ey >> ex >> ed; | |
ey -= 1; ex -= 1; ed -= 1; | |
cout << bfs() << "\n"; | |
return 0; | |
} |
