Skip to content

Commit 92f1fae

Browse files
committed
solved(python): programmers
- 연습문제 / 미로 탈출
1 parent 4c70b9f commit 92f1fae

File tree

4 files changed

+100
-0
lines changed

4 files changed

+100
-0
lines changed

programmers/python/연습문제/미로_탈출/__init__.py

Whitespace-only changes.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import itertools
2+
3+
from typing import List, Tuple
4+
from collections import deque
5+
6+
def solution(maps: List[str]) -> int:
7+
n, m = len(maps), len(maps[0])
8+
start = [
9+
(x, y)
10+
for x, y in itertools.product(range(m), range(n))
11+
if maps[y][x] == 'S'
12+
][0]
13+
14+
lever, lever_step = find_path(maps, start, "L")
15+
if lever_step == -1:
16+
return -1
17+
18+
end_step = find_path(maps, lever, "E")[1]
19+
if end_step == -1:
20+
return -1
21+
22+
return lever_step + end_step
23+
24+
25+
def find_path(maps: List[str], start: Tuple[int, int], target: str) -> Tuple[Tuple[int, int], int]:
26+
n, m = len(maps), len(maps[0])
27+
queue, visited = deque([(0, start)]), set()
28+
29+
while queue:
30+
step, (x, y) = queue.popleft()
31+
if (x, y) in visited:
32+
continue
33+
34+
visited.add((x, y))
35+
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
36+
nx, ny = x + dx, y + dy
37+
if not (0 <= nx < m and 0 <= ny < n):
38+
continue
39+
40+
if maps[ny][nx] == target:
41+
return (nx, ny), step + 1
42+
43+
if maps[ny][nx] != 'X':
44+
queue.append((step + 1, (nx, ny)))
45+
46+
return (-1, -1), -1
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
[
2+
{
3+
"params": [
4+
[
5+
"SOOOL",
6+
"XXXXO",
7+
"OOOOO",
8+
"OXXXX",
9+
"OOOOE"
10+
]
11+
],
12+
"expected": 16
13+
},
14+
{
15+
"params": [
16+
[
17+
"LOOXS",
18+
"OOOOX",
19+
"OOOOO",
20+
"OOOOO",
21+
"EOOOO"
22+
]
23+
],
24+
"expected": -1
25+
}
26+
]
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import json
2+
import os
3+
import unittest
4+
5+
from parameterized import parameterized
6+
7+
from .main import solution
8+
9+
10+
def load_sample(filename: str):
11+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
12+
13+
with open(path, "r") as file:
14+
return [(case["params"], case["expected"]) for case in json.load(file)]
15+
16+
17+
class TestCase(unittest.TestCase):
18+
@parameterized.expand(load_sample("sample.json"))
19+
def test_case(self, params: list, expected: any):
20+
# When
21+
result = solution(*params)
22+
23+
# Then
24+
self.assertEqual(expected, result)
25+
26+
27+
if __name__ == "__main__":
28+
unittest.main()

0 commit comments

Comments
 (0)