Let's consider a matrix of integers m
:
[[1,2,3]
[4,5,6]
[7,8,9]]
Which represents a graph:
(1)
/ \
(4) (2)
/ \ / \
(7) (5) (3)
\ / \ /
(8) (6)
\ /
(9)
There are two implementations of traversals bfs
and dfs
.
BFS uses queue
, DFS uses stack
, since there is no stack
data structure in python both could be implemented using simple list
or any other arbitrarily chosen data structure, which behaves like a queue
and stack
respectively, I opted for deque
.
def bfs_iterative(matrix, i, j, visited=None):
if not matrix:
return
values = [matrix[i][j]]
rows, cols = len(matrix), len(matrix[0])
visited = visited if visited else set()
queue = deque([(i, j)])
visited.add((i, j))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while queue:
row, col = queue.popleft()
for dr, dc in directions:
r, c = row + dr, col + dc
if r not in range(rows):
continue
if c not in range(cols):
continue
if (r, c) in visited:
continue
queue.append((r, c))
visited.add((r, c))
values.append(matrix[r][c])
return values
def dfs_iterative(matrix, i, j, visited=None):
if not matrix:
return
values = []
rows, cols = len(matrix), len(matrix[0])
visited = visited if visited else set()
stack = deque()
stack.append((i, j))
directions = [
(0, -1),
(0, 1),
(-1, 0),
(1, 0),
]
while stack:
row, col = stack.pop()
if (row, col) not in visited:
visited.add((row, col))
values.append(matrix[row][col])
for dr, dc in directions:
r, c = row + dr, col + dc
if r not in range(rows):
continue
if c not in range(cols):
continue
if (r, c) in visited:
continue
stack.append((r, c))
return values
Depending on the order of directions in bfs
the output of the values will be:
[1,4,2,7,5,3,8,6,9] or [1,2,4,3,5,7,6,8,9], which probably doesn't matter since "levels" are diagonals and the levels are in correct order (top to down), the elements are left to right or right to left.
But for dfs
there are more possible outputs and I wonder whether my implementation is off or each of those outputs is correct. Since for BST
there are in-order, post-order, pre-order traversals and each is valid and each is dfs
I think the 2nd option, but I cannot find a decent read about that actually.
Found A BFS and DFS implementation which sort of tackles this question.