Algorithm/Programmers
[Algorithm] Programmers :: 미로 탈출
MaxLevel
2023. 6. 15. 03:14
https://school.programmers.co.kr/learn/courses/30/lessons/159993
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
|
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
struct Node
{
int y;
int x;
int count;
};
bool visited[101][101] = { false };
int dir[4][2] = { {-1,0}, {1,0}, {0,-1}, {0,1} };
int Find(int startY, int startX, char target, vector<string>& maps)
{
memset(visited, false, sizeof(visited));
queue<Node> q;
q.push({ startY,startX,0 });
while (!q.empty())
{
int curY = q.front().y;
int curX = q.front().x;
int curCount = q.front().count;
q.pop();
if (maps[curY][curX] == target)
{
return curCount;
}
for (int i = 0; i < 4; ++i)
{
int nextY = curY + dir[i][0];
int nextX = curX + dir[i][1];
if (nextY < 0 || nextY >= maps.size()) continue;
if (nextX < 0 || nextX >= maps[0].size()) continue;
if (maps[nextY][nextX] == 'X') continue;
if (visited[nextY][nextX]) continue;
visited[nextY][nextX] = true;
q.push({ nextY,nextX,curCount + 1 });
}
}
return -1;
}
int solution(vector<string> maps) {
int answer = 0;
Node start, lever;
for (int i = 0; i < maps.size(); ++i)
{
for (int j = 0; j < maps[i].size(); ++j)
{
if (maps[i][j] == 'S') start = { i,j };
else if (maps[i][j] == 'L') lever = { i,j };
}
}
int toLever = Find(start.y, start.x, 'L',maps);
int toEscape = Find(lever.y, lever.x, 'E', maps);
if (toLever == -1 || toEscape == -1) return -1;
return toLever + toEscape;
}
|
cs |
BFS 기본예제로 적합한 것 같다.