Skip to main content

05 tree and graph

for BFS, DFS, Recursion etc we will need these easy concepts to help us

Understanding row and column​

This is a row - horizontal one so here we have 4 rows.

Define row,cols This helps in defining boundry conditions for recursion, make visited matrix etc.​

rows = len(grid)
cols = len(grid[0]) if grid else 0

Define boundry conditions​

if 0 <= i < rows and 0 <= j < cols:
print(grid[i][j])

Make visited matrix​

visited=[[False]*cols for _ in range(rows)]

Stack = we return to same thing. => Dfs Queue = we remove the first element => BFS

BFS (Breadth-First Search)DFS (Depth-First Search)
def bfs(i,j):
    queue=[(i,j)]
    while queue:
        x,y=queue.pop(0)
        if (x<0 or x>=rows or y<0 or y>=cols):
            continue
        elif visited[x][y]:
            continue
        elif grid[x][y]=="0":
            continue
        else:
            visited[x][y]=True
            print(f"Visiting cell: ({x},{y})")
            queue.append((x+1,y))
            queue.append((x-1,y))
            queue.append((x,y+1))
            queue.append((x,y-1))
def dfs(i,j):
    stack=[(i,j)]
    while stack:
        x,y=stack.pop()
        if (x<0 or x>=rows or y<0 or y>=cols):
            continue
        elif visited[x][y]:
            continue
        elif grid[x][y]=="0":
            continue
        else:
            visited[x][y]=True
            print(f"Visiting cell: ({x},{y})")
            stack.append((x+1,y))
            stack.append((x-1,y))
            stack.append((x,y+1))
            stack.append((x,y-1))

The General Idea​

1- Put first element in stack/queue in start
2-Take the processing element [ (0) in queue for bfs and last for stack in dfs]

checking phase​

3- Check cell boundry validity
4- Check visited validity
5- Check Question Condition validity

operation phase​

6- All checks are passed then mark the cell as visited
7- Do whatever question says with this element
8- Add every of its neighbours in the stack/queue