Skip to content

Commit 87c434e

Browse files
committed
solove question 23
1 parent 4938547 commit 87c434e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

first50.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1272,6 +1272,78 @@ def test_22():
12721272
assert getOriginalWords(s, words) == ["bedbath", "and", "beyond"]
12731273

12741274

1275+
"""
1276+
question 23
1277+
You are given an M by N matrix consisting of booleans that represents
1278+
a board. Each True boolean represents a wall. Each False boolean
1279+
represents a tile you can walk on.
1280+
1281+
Given this matrix, a start coordinate, and an end coordinate, return
1282+
the minimum number of steps required to reach the end coordinate from
1283+
the start. If there is no possible path, then return null. You can move up,
1284+
left, down, and right. You cannot move through walls.
1285+
You cannot wrap around the edges of the board.
1286+
1287+
For example, given the following board:
1288+
1289+
[[f, f, f, f],
1290+
[t, t, f, t],
1291+
[f, f, f, f],
1292+
[f, f, f, f]]
1293+
and start = (3, 0) (bottom left) and end = (0, 0) (top left),
1294+
the minimum number of steps required to reach the end is 7,
1295+
since we would need to go through (1, 2) because there is a wall everywhere
1296+
else on the second row.
1297+
-----------------
1298+
1299+
From starting point, try every possible paths until reaching the end point.
1300+
Both DFS and BFS work fine here.
1301+
But to find the minimum steps, we need to use BFS.
1302+
"""
1303+
1304+
1305+
def getMinSteps(matrix, starting, ending):
1306+
ROLS, COLS = len(matrix), len(matrix[0])
1307+
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
1308+
queue = deque()
1309+
visited = [[0 for _ in range(COLS)] for _ in range(ROLS)]
1310+
queue.append(starting)
1311+
visited[starting[0]][starting[1]] = 1
1312+
steps = 1
1313+
while queue:
1314+
for _ in range(len(queue)):
1315+
r, c = queue.popleft()
1316+
# try all the directions to go forward
1317+
for dr, dc in directions:
1318+
newr, newc = r + dr, c + dc
1319+
# filter out invalid/already-visited/wall cells
1320+
if (
1321+
newr < 0
1322+
or newr >= ROLS
1323+
or newc < 0
1324+
or newc >= COLS
1325+
or visited[newr][newc]
1326+
or matrix[newr][newc] == "t"
1327+
):
1328+
continue
1329+
if (newr, newc) == ending:
1330+
return steps
1331+
visited[newr][newc] = 1
1332+
queue.append((newr, newc))
1333+
steps += 1
1334+
return -1
1335+
1336+
1337+
def test_23():
1338+
matrix = [
1339+
["f", "f", "f", "f"],
1340+
["t", "t", "f", "t"],
1341+
["f", "f", "f", "f"],
1342+
["f", "f", "f", "f"],
1343+
]
1344+
assert getMinSteps(matrix, (3, 0), (0, 0)) == 7
1345+
1346+
12751347
"""
12761348
question 32 TODO
12771349
This problem was asked by Jane Street.

0 commit comments

Comments
 (0)