티스토리 뷰
1. 문제 링크
https://www.acmicpc.net/problem/6087
6087번: 레이저 통신
문제 크기가 1×1인 정사각형으로 나누어진 W×H 크기의 지도가 있다. 지도의 각 칸은 빈 칸이거나 벽이며, 두 칸은 'C'로 표시되어 있는 칸이다. 'C'로 표시되어 있는 두 칸을 레이저로 통신하기 위해서 설치해야 하는 거울 개수의 최솟값을 구하는 프로그램을 작성하시오. 레이저로 통신한다는 것은 두 칸을 레이저로 연결할 수 있음을 의미한다. 레이저는 C에서만 발사할 수 있고, 빈 칸에 거울('/', '\')을 설치해서 방향을 90도 회전시킬 수 있다.
www.acmicpc.net
2. 소스코드
#include <cstdio>
#include <deque>
#include <vector>
#include <algorithm>
using namespace std;
char map[100][100];
struct COORD {
int y, x;
int time;
int dir;
};
vector<COORD>start;
int r, c;
const int dx[] = { 0,1,0,-1 };
const int dy[] = { -1,0,1,0 };
int bfs(int firstdir)
{
deque<COORD>q;
bool visited[100][100] = { false, };
COORD ns;
ns.y = start[0].y + dy[firstdir];
ns.x = start[0].x + dx[firstdir];
ns.dir = firstdir;
ns.time = 0;
if (ns.x < 0 || ns.y < 0 || ns.x >= c || ns.y >= r || map[ns.y][ns.x] == '*')
return 0x7fffffff;
q.push_back(ns);
visited[start[0].y][start[0].x] = true;
visited[ns.y][ns.x] = true;
while (!q.empty())
{
COORD cur = q.front(); q.pop_front();
if (cur.y == start[1].y && cur.x == start[1].x)
{
return cur.time;
}
for (int dir = 0; dir < 4; dir++)
{
COORD next;
next.y = cur.y + dy[dir];
next.x = cur.x + dx[dir];
next.dir = dir;
if (next.y < 0 || next.x < 0 || next.y >= r || next.x >= c || visited[next.y][next.x]
||map[next.y][next.x] =='*')
continue;
if (next.dir != cur.dir)
{
next.y = cur.y;
next.x = cur.x;
next.time = cur.time + 1;
q.push_back(next);
}
else
{
next.time = cur.time;
visited[next.y][next.x] = true;
q.push_front(next);
}
}
}
}
int main(void)
{
scanf("%d %d ", &c, &r);
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++){
scanf("%c", &map[i][j]);
if (map[i][j] == '\n'){
j--;
continue;
}
if (map[i][j] == 'C'){
COORD s;
s.y = i, s.x = j;
s.time = 0;
start.push_back(s);
}
}
int ret = 0x7fffffff;
ret = min(ret, bfs(0));
ret = min(ret, bfs(1));
ret = min(ret, bfs(2));
ret = min(ret, bfs(3));
printf("%d", ret);
return 0;
}
'알고리즘 > BFS' 카테고리의 다른 글
BOJ, 백준) 17135 캐슬디펜스 ( C / C++) (0) | 2020.01.08 |
---|---|
[백준] 3187. 양치기 꿍 ( C / C++) (0) | 2019.12.24 |
[백준] 1981. 배열에서 이동 ( C / C++) (0) | 2019.12.24 |
[백준] 3917. 백조의 호수 ( C / C++) (0) | 2019.12.24 |
boj, 백준) 9376. 탈옥 ( C / C++) (0) | 2019.12.24 |
댓글