명령 1. Go k: k는 1, 2 또는 3일 수 있다. 현재 향하고 있는 방향으로 k칸 만큼 움직인다
명령 2. Turn dir: dir은 left 또는 right 이며, 각각 왼쪽 또는 오른쪽으로 90° 회전한다.
동에서 서, 북에서 남으로 회전하는 데는 명령을 두번 해야한다
현재 방향에서 한 번의 명령으로 최대 3칸까지 이동이 가능하다.
벽을 통과할 수는 없다.
2.접근방법[알고리즘]
이 문제는 시작 지점에서 종료 지점 까지 가는데 필요한 최소 명령의 수를 구해야 한다.
한 번의 명령마다 방향전환을 하거나 이동을 한다.
특정 지점을 방문했을 때 단순히 좌표만 저장 하는 게 아니라, 방향에 대한 정보까지 저장을 해주어야한다.
그래서 이전에 방문했는지 체크해주는 배열을 3차원 배열로 만들어
vis[x][y][동 or 서 or 남 or 북] x, y 좌표에 대해서
동, 서, 남 , 북 방향 상태까지 필요햔 명령의 수를 체크해야한다.
하나의 좌표마다 행동할 수 있는 경우의 수는
현재 방향에서 1칸, 2칸, 3칸 이동하기와
현재 방향을 제외한 나머지 방향으로 방향전환 하기가 있다.
한 번의 명령으로 1칸 2칸 3칸 모두 이동하는 게 가능하지만,
방향을 전환 하는데는 동에서 서로 방향을 전환하거나 남에서 북으로 방향을 전환한다면 2번의 명령이 필요하다.
이 때 2번의 명령이 필요한 경우 방향을 전환했다고 바로 방문을 했다고 체크하는 게 아니라
나중에 큐에서 나올 때 체크해주어야한다.
왜냐하면 x,y가 도착지점일 때 x,y에서 방향을 전환하는데 2번 명령을 하는 동안
다른 점에서 한번만에 도착하는 경우도 있기 때문이다.
결과적으로 도착점까지 최소 명령의 수를 구해야하기 때문에 우선순위 큐를 이용했다.
명령의 수를 최소힙으로 계속 pop해주면서 로봇이 최소 명령으로 하는 행동을 먼저하게 한다.
그러다 도착지점에 다다르면 바로 해당 도착지점에 오기까지 필요했던 명령의 수를 바로 리턴해주었다.
우선순위큐를 사용하지 않으면?
만약 우선순위큐를 사용하지 않는다면
도착지점에 도착했다고 바로 리턴해주면 안된다.
방향전환하는데 명령이 2번 일어나는 경우도 있어서
큐에서 뒤에 나오는 경우가 더 적은 명령의 수로 일어나는 행동일 수도 있기 때문이다.
즉 BFS를 돌지만 다른 문제와 다르게 큐에서 뒤에서 나오는 결과가 정답일 수도 있다.
3.문제풀이코드
첫 정답코드
#include <bits/stdc++.h>
using namespace std;
//회전시키는데 명령 1, 현재 방향에서 이동하는데 명령 1,
int n, m, arr[105][105], sx, sy, sd, ex, ey, ed, ans = INT_MAX;
bool vis[105][105][5]; //1동 2서 3남 4북 방향 정보까지 받는다
struct Edge {
int x, y, d, cnt;
Edge(int a, int b, int c, int e) {
x = a;
y = b;
d = c;
cnt = e;
}
bool operator<(const Edge& bb) const {
return cnt > bb.cnt;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
priority_queue<Edge> Q;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> arr[i][j];
}
}
cin >> sx >> sy >> sd;
cin >> ex >> ey >> ed;
vis[sx][sy][sd] = 1;
Q.push(Edge(sx, sy, sd, 0));
while (!Q.empty()) {
int x = Q.top().x;
int y = Q.top().y;
int d = Q.top().d;
int cnt = Q.top().cnt;
Q.pop();
vis[x][y][d] = 1;
//if(d==1)
// cout << x <<' ' << y << " " << "동" << " " << cnt<< '\n';
//else if(d==2)
// cout << x << ' ' << y << " " << "서" << " " << cnt<< '\n';
//else if (d == 3)
// cout << x << ' ' << y << " " << "남" << " " << cnt<< '\n';
//else if (d == 4)
// cout << x << ' ' << y << " " << "북" << " " << cnt<< '\n';
if (x == ex && y == ey && d == ed) {
ans = min(cnt, ans);
}
// 현재 방향에서 이동
// d == 1 : nx : 0 / ny : 1, 2, 3
// d == 2 : nx : 0 / ny : -1, -2, -3;
// d == 3 : nx: 1 , 2 , 3 / ny : 0
// d == 4 : nx : -1 -2 -3 / ny : 0;
if (d == 1) {
for (int i = 1; i <= 3; i++) {
if (y + i > m) break;
if (arr[x][y + i] == 1) break;
if (vis[x][y + i][d] == 0) {
vis[x][y + i][d] = 1;
Q.push(Edge{ x,y + i,d ,cnt + 1 });
}
}
}
else if (d == 2) {
for (int i = 1; i <= 3; i++) {
if (y - i < 1) break;
if (arr[x][y - i] == 1) break;
if (vis[x][y - i][d] == 0) {
vis[x][y - i][d] = 1;
Q.push(Edge{ x,y - i,d ,cnt + 1 });
}
}
}
else if (d == 3) {
for (int i = 1; i <= 3; i++) {
if (x + i > n) break;
if (arr[x + i][y] == 1) break;
if (vis[x + i][y][d] == 0) {
vis[x + i][y][d] = 1;
Q.push(Edge{ x + i,y,d ,cnt + 1 });
}
}
}
else if (d == 4) {
for (int i = 1; i <= 3; i++) {
if (x - i < 1) break;
if (arr[x - i][y] == 1) break;
if (vis[x - i][y][d] == 0) {
vis[x - i][y][d] = 1;
Q.push(Edge{ x - i,y,d ,cnt + 1 });
}
}
}
//방향전환 명령
for (int i = 1; i <= 4; i++) {
if (i == d) continue;
if (vis[x][y][i] == 0) {
if ((d == 1 && i == 2) || (d == 2 && i == 1)) {
Q.push(Edge(x, y, i, cnt + 2));
}
else if ((d == 3 && i == 4) || (d == 4 && i == 3)) {
Q.push(Edge(x, y, i, cnt + 2));
}
else {
vis[x][y][i] = 1;
Q.push(Edge(x, y, i, cnt + 1));
}
}
}
}
cout << ans;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
//회전시키는데 명령 1, 현재 방향에서 이동하는데 명령 1,
int n, m, arr[105][105], sx, sy, sd, ex, ey, ed, ans = INT_MAX;
bool vis[105][105][5]; //1동 2서 3남 4북 방향 정보까지 받는다
struct Edge {
int x, y, d, cnt;
Edge(int a, int b, int c, int e) {
x = a;
y = b;
d = c;
cnt = e;
}
bool operator<(const Edge& bb) const {
return cnt > bb.cnt;
}
};
priority_queue<Edge> Q;
void move(int x, int y, int d, int cnt) {
if (d == 1) {
for (int i = 1; i <= 3; i++) {
if (y + i > m) break;
if (arr[x][y + i] == 1) break;
if (vis[x][y + i][d] == 0) {
vis[x][y + i][d] = 1;
Q.push(Edge{ x,y + i,d ,cnt + 1 });
}
}
}
else if (d == 2) {
for (int i = 1; i <= 3; i++) {
if (y - i < 1) break;
if (arr[x][y - i] == 1) break;
if (vis[x][y - i][d] == 0) {
vis[x][y - i][d] = 1;
Q.push(Edge{ x,y - i,d ,cnt + 1 });
}
}
}
else if (d == 3) {
for (int i = 1; i <= 3; i++) {
if (x + i > n) break;
if (arr[x + i][y] == 1) break;
if (vis[x + i][y][d] == 0) {
vis[x + i][y][d] = 1;
Q.push(Edge{ x + i,y,d ,cnt + 1 });
}
}
}
else if (d == 4) {
for (int i = 1; i <= 3; i++) {
if (x - i < 1) break;
if (arr[x - i][y] == 1) break;
if (vis[x - i][y][d] == 0) {
vis[x - i][y][d] = 1;
Q.push(Edge{ x - i,y,d ,cnt + 1 });
}
}
}
}
void turn_dir(int x, int y, int d, int cnt) {
for (int i = 1; i <= 4; i++) {
if (i == d) continue;
if (vis[x][y][i] == 0) {
if ((d == 1 && i == 2) || (d == 2 && i == 1)) {
// 바로 방문 체크를 하면 안된다. 방향전환 하는 동안 먼저 방문하는 경우가 있을 수도 있다.
Q.push(Edge(x, y, i, cnt + 2));
}
else if ((d == 3 && i == 4) || (d == 4 && i == 3)) {
Q.push(Edge(x, y, i, cnt + 2));
}
else {
vis[x][y][i] = 1;
Q.push(Edge(x, y, i, cnt + 1));
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
//입력
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> arr[i][j];
}
}
cin >> sx >> sy >> sd;
cin >> ex >> ey >> ed;
vis[sx][sy][sd] = 1;
Q.push(Edge(sx, sy, sd, 0));
while (!Q.empty()) {
int x = Q.top().x;
int y = Q.top().y;
int d = Q.top().d;
int cnt = Q.top().cnt;
Q.pop();
vis[x][y][d] = 1;
if (x == ex && y == ey && d == ed) {
cout << cnt;
return 0;
}
// 현재 방향에서 이동
move(x, y, d, cnt);
//방향전환 명령
turn_dir(x,y,d,cnt);
}
return 0;
}
각각의 큐를 만들고 시간을 증가시키면서 새로 방문한 노드에 대해서 일괄적으로 상하좌우 탐색한다.
고슴도치는 물이 방문할 점을 방문할 수 없기 때문에
물 -> 고슴도치 -> 물 -> 고슴도치 순으로 BFS를 돈다.
3.문제풀이코드 C++
#include <bits/stdc++.h>
using namespace std;
int r, c;
char arr[53][53];
bool s_check[53][53], wt_check[53][53];
int ch[53][53];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
//물 먼저 이동 후 고슴도치 이동
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> r >> c;
queue<pair<int, int> > wt;
queue<pair<int, int> > s;
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
cin >> arr[i][j];
if (arr[i][j] == '*') {
ch[i][j] = -1;
wt.push({ i,j });
wt_check[i][j] = 1;
}
else if (arr[i][j] == 'S') {
ch[i][j] = 1;
s.push({ i,j });
s_check[i][j] = 1;
}
else if (arr[i][j] == 'X') {
ch[i][j] = 2;
}
else if (arr[i][j] == 'D') {
ch[i][j] = 3;
}
}
}
int t = 0;
while (true) {
int s_size = s.size();
int wt_size = wt.size();
if (s_size == 0) break;
for (int i = 0; i < wt_size; i++) {
int x = wt.front().first;
int y = wt.front().second;
wt.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx <= 0 || nx > r || ny <= 0 || ny > c||wt_check[nx][ny] == 1) continue;
if (ch[nx][ny] == 0 || ch[nx][ny]==1) {
wt_check[nx][ny] = 1;
ch[nx][ny] = -1;
wt.push({ nx,ny });
}
}
}
for (int i = 0; i < s_size; i++) {
int x = s.front().first;
int y = s.front().second;
s.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx <= 0 || nx > r || ny <= 0 || ny > c || s_check[nx][ny] == 1) continue;
if (ch[nx][ny] == 0 || ch[nx][ny] == 1 ) {
ch[nx][ny] = 1;
s_check[nx][ny] = 1;
s.push({ nx,ny });
}
else if (ch[nx][ny] == 3) {
cout << t+1;
return 0;
}
}
}
t++;
//print();
}
cout << "KAKTUS" << '\n';
return 0;
}
백준 3055번 탈출 메모리 시간
틀린이유
처음에 고슴도치와 물이 방문한 좌표를 체크해주지 않아 틀렸다
BFS든 DFS든 방문해준 점을 체크표시해주지 않으면 방문한 곳을 계속 방문해서 무한 루프에 빠지고 만다.
4. DFS를 돌면서 현재 좌표에 -1이 저장되어 있지 않다면 탈출이 가능한지 불가능한지 이미 구해졌으므로
그 값을 리턴해준다.
3.문제풀이코드 C++
#include <bits/stdc++.h>
using namespace std;
//방문한 곳을 다시 방문하면 종료
int n, m, ans, dy[503][503];
char arr[503][503];
int DFS(int x, int y) {
char a = arr[x][y];
// 미로 탈출
if (a == '\0') return 1;
int& cur = dy[x][y];
//x,y가 이미 방문한 점이라면
if (cur != -1) {
return cur;
}
// 방문 표시
cur = 0;
if (a == 'U') {
cur = DFS(x - 1, y);
}
else if (a == 'R') {
cur = DFS(x, y + 1);
}
else if (a == 'D') {
cur = DFS(x + 1, y);
}
else if (a == 'L') {
cur = DFS(x, y - 1);
}
return cur;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> arr[i][j];
dy[i][j] = -1;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ans += DFS(i,j);
}
}
cout << ans <<'\n';
}
모든 영역은 비활성화 바이러스거나 활성화 바이러스거나 상관 없이 바이러스이기만 하면 된다.
문제풀이과정
1. DFS를 통해 m개의 비활성화 바이러스를 선택해 활성화 바이러스로 만든다.
2. 선택된 활성화바이러스로 BFS를 하고, 벽을 제외한 모든영역에 바이러스를 퍼트리는 시간을 구한다.
3. DFS를 돌며 m개를 다르게 선택하며 최소 시간을 구해준다.
4. 바이러스를 어떤 방법으로도 전체 영역에 퍼트릴 수 없다면 -1, 아니면 최소시간을 출력한다.
3.문제풀이코드 C++
#include <bits/stdc++.h>
using namespace std;
int n, m, arr[51][51], ans=INT_MAX, total_zero;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
bool ch[51][51];
bool virus_select[11];
vector<pair<int, int> > virus;
queue<pair<int,int> > Q;
void BFS() {
int count_zero = 0;
//활성화된 바이러스 Q에 넣어줌
for (int i = 0; i < virus.size(); i++) {
if (virus_select[i] == 1) {
Q.push({ virus[i].first, virus[i].second});
ch[virus[i].first][virus[i].second] = 1;
}
}
int time = 0;
while (!Q.empty()) {
int cur_size = Q.size();
/*0인 영역에 바이러스를 다 퍼트렸는지 체크*/
if (total_zero == count_zero) {
ans = min(time, ans);
while (!Q.empty()) Q.pop();
break;
}
/*같은 시간에 새로 추가된 모든 바이러스를 BFS로 탐색*/
for (int j = 0; j < cur_size; j++) {
int x = Q.front().first;
int y = Q.front().second;
Q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if (arr[nx][ny] == -1) continue; //벽이면 continue
if (ch[nx][ny] == 0) { //비활성화된 바이러스, 0인 영역 모두 방문
ch[nx][ny] = 1;
Q.push({ nx, ny });
if (arr[nx][ny] == 0) count_zero++; //0인 영역을 방문한 거라면 0인 영역에 바이러스 퍼진 갯수 세줌
}
}
}
time++;
}
//DFS에서 또 ch를 사용하므로 BFS함수 이전 원래 상태로 초기화
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
ch[i][j] = 0;
}
}
}
void DFS(int cur, int L) {
if (L == m) {
BFS();
}
else {
for (int i = cur; i < virus.size(); i++) {
virus_select[i] = 1;
DFS(i + 1, L + 1);
virus_select[i] = 0;
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (arr[i][j] == 2) virus.push_back({ i,j });
else if(arr[i][j] == 0) total_zero++;
}
}
DFS(0, 0);
if (ans == INT_MAX) {
cout << -1;
}
else {
cout << ans;
}
}
백준 17142 연구소3 해결 메모리 및 시간
4.틀린 이유
1. 시간초과 이유 : 바이러스를 벽을 제외한 모든 영역에 퍼트렸는지 확인
/*0인 영역에 바이러스를 다 퍼트렸는지 체크*/
if (total_zero == count_zero) {
ans = min(time, ans);
while (!Q.empty()) Q.pop();
break;
}
0의 개수를 세는 변수를 따로 설정해 바이러스가 된 0의 개수를 세서 비교했다.
이전에는 n*n 배열을 모두 탐색해 0이 있는지 없는지 확인해서 시간초과가 나서 틀렸다.
2. 비활성화된 바이러스도 바이러스다.
처음에 문제를 잘 이해하지 못해 모든 바이러스를 활성화 시켜야 끝나는 줄 알고 그렇게 했는데
1. 백트래킹으로 바이러스 놓는 칸 m개 선택 2. m개를 선택했을 때 바이러스 다 퍼트릴 수 있는 지 BFS해보고 퍼트릴 수 있다면 시간을 구한다. 3. m개를 선택하는 모든 방법에 대하여 시간을 구해보고 최소 시간을 뽑는다. 4. 어떤 방법으로도 바이러스를 모든 공간에 퍼트릴 수 없다면 -1을 출력한다.
3.문제풀이코드 C++
#include <bits/stdc++.h>
using namespace std;
int n, m, arr[51][51], ans=INT_MAX;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
vector<pair<int, int > > virus;
queue<pair<int, int> > Q;
//1. 바이러스 놓는 칸 m개 선택
//2. 바이러스 다 퍼트렸는지 확인
//3. 다 퍼트렸다면 최소시간 확인
//4. 다 퍼트린게 없다면 -1 출력
void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == -1) cout << '-' << ' ';
else cout << arr[i][j] <<' ';
}
cout << '\n';
}
cout << "------------\n";
}
int check() {
int minute = 0;
//print();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == -1) continue;
if (arr[i][j] == 0) {
return INT_MAX;
}
else {
minute = max(arr[i][j], minute);
}
}
}
return minute;
}
void BFS() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 1) {
Q.push({ i,j });
}
}
}
while (!Q.empty()) {
int x = Q.front().first;
int y = Q.front().second;
Q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if (arr[nx][ny] == 0) {
arr[nx][ny] = arr[x][y] + 1;
Q.push({ nx,ny });
}
}
}
}
void initialize() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] > 1) {
arr[i][j] = 0;
}
}
}
}
void DFS(int cur, int L) {
if (L == m) {
BFS();
ans = min(ans, check());
initialize();
}
else {
for (int i = cur; i < virus.size(); i++) {
//바이러스는 arr에서 1로 체크해준다.
int x = virus[i].first;
int y = virus[i].second;
if (arr[x][y] == 0) {
arr[x][y] = 1;
DFS(i + 1, L + 1);
arr[x][y] = 0;
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
queue<pair<int, int > > Q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (arr[i][j] == 1) {
arr[i][j] = -1;
}
if (arr[i][j] == 2) {
arr[i][j] = 0;
virus.push_back({ i,j });
}
}
}
DFS(0,0);
if (ans == INT_MAX) {
cout << -1;
}
else {
cout << ans-1;
}
}