Skip to content

Commit 5690b8d

Browse files
committed
Add follow up with matrix traversal
1 parent 317fc03 commit 5690b8d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

utilities/python/graph_dfs.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,28 @@ def dfs(i, j):
1717
for j in range(cols):
1818
dfs(i, j)
1919

20+
# Follow up:
21+
# 1) Diagonal cells are considered neighbors
22+
# 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc.
23+
def graph_dfs_diagonals(matrix):
24+
rows, cols = len(matrix), len(matrix[0])
25+
visited = set()
26+
# Change 1: Add 4 more diagonal directions.
27+
directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1))
28+
def dfs(i, j):
29+
if (i, j) in visited:
30+
return
31+
print(matrix[i][j])
32+
visited.add((i, j))
33+
for direction in directions:
34+
# Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around.
35+
next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols
36+
dfs(next_i, next_j)
37+
38+
for i in range(rows):
39+
for j in range(cols):
40+
dfs(i, j)
41+
2042
graph_dfs([
2143
[1, 2, 3, 4],
2244
[5, 6, 7, 8],

0 commit comments

Comments
 (0)