16/08/2025, 22:00 AI.
ipynb - Colab
# Define the tree as a dictionary
tree = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': ['H', 'I'],
'E': ['J', 'K'],
'F': ['L', 'M'],
'G': ['N', 'O'],
'H': [],
'I': [],
'J': ['P', 'Q', 'R', 'S'],
'P': [],
'Q': [],
'R': [],
'S': [],
'K': [],
'L': [],
'M': [],
'N': [],
'O': []
}
keyboard_arrow_down Tree Travershal using DFS
Here I have implemented the DFS algorithm using a recursion
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 1/9
16/08/2025, 22:00 AI.ipynb - Colab
def dfs_using_recursion(tree, node, visited = None):
if visited==None :
visited = []
visited.append(node)
print(node + '--->', end=' ')
for child in tree[node]:
dfs_using_recursion(tree, child, visited)
dfs_using_recursion(tree, 'A')
A---> B---> D---> H---> I---> E---> J---> P---> Q---> R---> S---> K---> C---> F---> L---> M---> G---> N---> O--->
DFS algorithm using Stack
def dfs_using_stack(tree, node, visited = None):
if visited==None :
visited = []
stack = [node] # here we are using a list as stack
while stack:
current_node = stack.pop() # list has push pop functions inbuilt
if current_node not in visited:
visited.append(current_node)
print(current_node + '--->', end=" ")
stack.extend(tree[current_node]) # this operations is basically executing multiple push
dfs_using_stack(tree, 'A')
A---> C---> G---> O---> N---> F---> M---> L---> B---> E---> K---> J---> S---> R---> Q---> P---> D---> I---> H--->
But the output for this is HRL... This is because the push() operation which is append() for list adds the elements from the right hand side.
Also, the pop() operations removes elements from the right.
To implement Top-Right-Left DFS we can use stack from the module collections
from collections import deque
def dfs_using_stack(tree, node, visited = None):
if visited==None :
visited = []
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 2/9
16/08/2025, 22:00 AI.ipynb - Colab
stack = deque([node])
while stack:
current_node = stack.pop() # list has push pop functions inbuilt
if current_node not in visited:
visited.append(current_node)
print(current_node + '--->', end=" ")
for child in reversed(tree[current_node]):
if child not in visited:
stack.extend(child)
dfs_using_stack(tree, 'A')
A---> B---> C---> D---> E---> F---> G---> H---> I---> J---> K---> L---> M---> N---> O---> P---> Q---> R---> S--->
keyboard_arrow_down Tree Travarshal with BFS
We can modify the previous code a little bit to make it a bfs
from collections import deque
def bfs_using_queue(tree, node, visited = None):
if visited==None :
visited = []
q = deque([node])
while q:
current_node = q.popleft() # list has push pop functions inbuilt
if current_node not in visited:
visited.append(current_node)
print(current_node + '--->', end=" ")
for child in tree[current_node]:
if child not in visited:
q.extend(child)
bfs_using_queue(tree, 'A')
A---> B---> C---> D---> E---> F---> G---> H---> I---> J---> K---> L---> M---> N---> O---> P---> Q---> R---> S--->
keyboard_arrow_down N-Queen Problem
The objective is to place N - number of Queens on a NxN chess board so that none of the Queen can attack each other
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 3/9
16/08/2025, 22:00 AI.ipynb - Colab
The NXN empty chess board can be represented by a NXN matrix with '0' entries and the positions of the queen can be represnted by '1' or 'Q'
So, start with a empty chess board of size N X N
global N
N = 4
board = [[0]*N]*N
board
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
printing board as 2D matrix
print(*board, sep="\n")
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
To place a "Queen" in any ij'th place of the board, we have to check whether that place is safe or not.
That means, we have to check whether there is another queen is present in entire i-th row, entire j-th column, the diagonal positions and the
off diagonal positions.
Lets create the function "safe_or_not"
def safe_or_not(board, row, col):
# # along the column
# for col in range(N):
# if board[row][col] == 'Q' :
# return False
# # along the diagonal
# r = row
# c = column
# while r>=0 and c>=0 :
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 4/9
16/08/2025, 22:00 AI.ipynb - Colab
# if board[r][c] == 'Q' :
# return False
# r = r-1
# c = c-1
# # along the off-diagonal
# r = row
# c = column
# while r>=0 and c<N :
# if board[r][c] == 'Q' :
# return False
# r = r-1
# c = c+1
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_nqueen(board,nth_queen):
# base case: If all queens are placed
# then return true
if nth_queen >= N:
return True
# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):
if safe_or_not(board, i, nth_queen):
# Place this queen in board[i][col]
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 5/9
16/08/2025, 22:00 AI.ipynb - Colab
board[i][nth_queen] = 1
# recur to place rest of the queens
if solve_nqueen(board, nth_queen + 1) == True:
return True
# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][nth_queen] = 0
# if the queen can not be placed in any row in
# this column col then return false
return False
global N
N = 4
board = [[0]*N]*N
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solve_nqueen(board, 0) == False:
print ("Solution does not exist")
return False
print(board)
return True
solveNQ()
[[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]]
True
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 6/9
16/08/2025, 22:00 AI.ipynb - Colab
global N
N = 4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 'Q':
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False
# along the column
# for col in range(N):
# if board[row][col] == 'Q' :
# return False
# r = row
# c = col
# while r>=0 and c>=0 :
# if board[r][c] == 'Q' :
# return False
# r = r-1
# c = c-1
# r = row
# c = col
# while r<N and c<N :
# if board[r][c] == 'Q' :
# return False
# r = r+1
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 7/9
16/08/2025, 22:00 AI.ipynb - Colab
# c = c+1
# r = row
# c = col
# while r>=0 and c<N :
# if board[r][c] == 'Q' :
# return False
# r = r-1
# c = c+1
# r = row
# c = col
# while r<N and c>=0 :
# if board[r][c] == 'Q' :
# return False
# r = r+1
# c = c-1
return True
def solveNQUtil(board, col):
# base case: If all queens are placed
# then return true
if col >= N:
return True
# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 'Q'
print(board)
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0
# if the queen can not be placed in any row in
# this column col then return false
return False
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 8/9
16/08/2025, 22:00 AI.ipynb - Colab
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# driver program to test above function
solveNQ()
File "<tokenize>", line 66
return True
^
IndentationError: unindent does not match any outer indentation level
https://colab.research.google.com/drive/1Zoz-GJsYhyai0Hd88hl4DCZCtCLAI0IV#printMode=true 9/9