성능 요약
메모리: 4.13 MB, 시간: 0.02 ms
문제 설명
1 x 1 크기의 칸들로 이루어진 직사각형 격자 형태의 미로에서 탈출하려고 합니다. 각 칸은 통로 또는 벽으로 구성되어 있으며, 벽으로 된 칸은 지나갈 수 없고 통로로 된 칸으로만 이동할 수 있습니다. 통로들 중 한 칸에는 미로를 빠져나가는 문이 있는데, 이 문은 레버를 당겨서만 열 수 있습니다. 레버 또한 통로들 중 한 칸에 있습니다. 따라서, 출발 지점에서 먼저 레버가 있는 칸으로 이동하여 레버를 당긴 후 미로를 빠져나가는 문이 있는 칸으로 이동하면 됩니다. 이때 아직 레버를 당기지 않았더라도 출구가 있는 칸을 지나갈 수 있습니다. 미로에서 한 칸을 이동하는데 1초가 걸린다고 할 때, 최대한 빠르게 미로를 빠져나가는데 걸리는 시간을 구하려 합니다.
미로를 나타낸 문자열 배열 maps
가 매개변수로 주어질 때, 미로를 탈출하는데 필요한 최소 시간을 return 하는 solution 함수를 완성해주세요. 만약, 탈출할 수 없다면 -1을 return 해주세요.
제한사항
- 5 ≤
maps
의 길이 ≤ 100- 5 ≤
maps[i]
의 길이 ≤ 100 maps[i]
는 다음 5개의 문자들로만 이루어져 있습니다.- S : 시작 지점
- E : 출구
- L : 레버
- O : 통로
- X : 벽
- 시작 지점과 출구, 레버는 항상 다른 곳에 존재하며 한 개씩만 존재합니다.
- 출구는 레버가 당겨지지 않아도 지나갈 수 있으며, 모든 통로, 출구, 레버, 시작점은 여러 번 지나갈 수 있습니다.
- 5 ≤
입출력 예
maps | result |
---|---|
["SOOOL","XXXXO","OOOOO","OXXXX","OOOOE"] | 16 |
["LOOXS","OOOOX","OOOOO","OOOOO","EOOOO"] | -1 |
입출력 예 설명
입출력 예 #1
주어진 문자열은 다음과 같은 미로이며
다음과 같이 이동하면 가장 빠른 시간에 탈출할 수 있습니다.
4번 이동하여 레버를 당기고 출구까지 이동하면 총 16초의 시간이 걸립니다. 따라서 16을 반환합니다.
입출력 예 #2
주어진 문자열은 다음과 같은 미로입니다.
시작 지점에서 이동할 수 있는 공간이 없어서 탈출할 수 없습니다. 따라서 -1을 반환합니다.
코드
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
struct Node {
int row, col, cost, heuristic;
Node(int r, int c, int cst, int h) : row(r), col(c), cost(cst), heuristic(h) {}
bool operator>(const Node& other) const {
return cost + heuristic > other.cost + other.heuristic;
}
};
int calculateHeuristic(int currentRow, int currentCol, int targetRow, int targetCol) {
return abs(targetRow - currentRow) + abs(targetCol - currentCol);
}
int AStar(const vector<string>& maps, int startRow, int startCol, int targetRow, int targetCol) {
int rows = maps.size();
int cols = maps[0].size();
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
priority_queue<Node, vector<Node>, greater<Node>> pq;
// 방향 설정
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
// 시작 노드를 우선순위 큐에 넣기
pq.push(Node(startRow, startCol, 0, calculateHeuristic(startRow, startCol, targetRow, targetCol)));
while (!pq.empty()) {
Node current = pq.top();
pq.pop();
int r = current.row;
int c = current.col;
if (r == targetRow && c == targetCol) {
// 출구에 도달
return current.cost;
}
if (!visited[r][c]) {
visited[r][c] = true;
//주변 노드 확인
for (int i = 0; i < 4; ++i) {
int nr = r + dr[i];
int nc = c + dc[i];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maps[nr][nc] != 'X' && !visited[nr][nc]) {
int newCost = current.cost + 1;
int heuristic = calculateHeuristic(nr, nc, targetRow, targetCol);
pq.push(Node(nr, nc, newCost, heuristic));
}
}
}
}
// 우선순위 큐가 비어있고 출구에 도달하지 않았다면 유효한 경로가 없음
return -1;
}
int solution(vector<string> maps)
{
int answer = 0;
int rows = maps.size();
int cols = maps[0].size();
int startRow, startCol, endRow, endCol, leverRow, leverCol;
// 시작 지점, 출구 및 레버의 위치를 찾기
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (maps[i][j] == 'S') {
startRow = i;
startCol = j;
} else if (maps[i][j] == 'E') {
endRow = i;
endCol = j;
} else if (maps[i][j] == 'L') {
leverRow = i;
leverCol = j;
}
}
}
int cost = 0;
cost = AStar(maps, startRow, startCol, leverRow, leverCol);
if(cost < 0)
return -1;
answer += cost;
cost = AStar(maps, leverRow, leverCol, endRow, endCol);
if(cost < 0)
return -1;
answer += cost;
return answer;
}
테스트 결과
'코딩테스트' 카테고리의 다른 글
[백준][Gold I] 외판원 순회 - 2098 (1) | 2024.01.06 |
---|---|
[백준][Gold IV] 줄세우기 - 2631 (0) | 2024.01.06 |
[level 2] 교점에 별 만들기 - 87377 (1) | 2023.12.26 |
[level 2] 괄호 변환 - 60058 (0) | 2023.12.25 |
[level 2] 쿼드압축 후 개수 세기 - 68936 (0) | 2023.11.25 |