In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When recursively traversing the matrix, always ensure that your next position is within the boundary of the matrix. More tips for doing depth-first searches on a matrix can be found [here](https://discuss.leetcode.com/topic/66065/python-dfs-bests-85-tips-for-all-dfs-in-matrix-question/). A simple template for doing depth-first searches on a matrix goes like this:
```py
from collections import namedtuple, deque
# Create point and direction data structures
Point = namedtuple("Point", ["x", "y"])
Direction = namedtuple("Direction", ["x", "y"])
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When traversing the matrix, always ensure that your current position is within the boundary of the matrix and has not been visited before.
A simple template for doing depth-first searches on a matrix goes like this:
# Adding from the right side for both queue and stack
store.append(Point(new_x, new_y))
store.append((new_x, new_y))
# Depends upon the question: many grid questions have blocked cells.
# This implementation assumes 0s represent valid and 1s represent invalid
def is_valid(point):
return matrix[point[0]][point[1]] == 0
def pass_all_conditions(current_point):
return current_point[0] in range(rows) and current_point[1] in range(cols) \
and current_point not in visited and is_valid(current_point)
# Handle disjointed graphs
for x in range(rows):
for y in range(cols):
store = deque([Point(x, y)])
while store:
if method == "BFS":
current_point = store.popleft()
else:
current_point = store.pop()
if pass_all_conditions(current_point):
add_neighbours(store, current_point)
```
> NOTE: While DFS is implemented using recursion in this sample, it could also be implemented iteratively similar to BFS. The key difference between the algorithms lies in the underlying data structure (BFS uses a queue while DFS uses a stack). The `deque` class in Python can function as both a stack and a queue
For additional tips on BFS and DFS, you can refer to this [LeetCode post](https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90774/Python-solution-with-detailed-explanation)