Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions NxNgrphColor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
n=int(input())
adjDic={}
for i in range(n*n):
if (i%n==0):
adjDic[i]=list()
adjDic[i].append(i+1)
if (i+n<(n*n)):
adjDic[i].append(i+n)
if (i-n>=0):
adjDic[i].append(i-n)
if (i-(n-1)>=0):
adjDic[i].append(i-(n-1))
if (i+(n+1)<n*n):
adjDic[i].append(i+n+1)

elif (i%n==n-1):
adjDic[i]=list()
adjDic[i].append(i-1)
if (i+n<(n*n)):
adjDic[i].append(i+n)
if (i-n>0):
adjDic[i].append(i-n)
if (i-(n+1)>0):
adjDic[i].append(i-(n+1))
if (i+(n-1)<n*n):
adjDic[i].append(i+(n-1))
else:
if (i+n<n*n):
adjDic[i]=list()
adjDic[i].append(i+n)
if (i-n>0):
if adjDic.get(i):
adjDic[i].append(i-n)
else:
adjDic[i]=list()
adjDic[i].append(i-n)
adjDic[i].append(i+1)
adjDic[i].append(i-1)
if (i-(n-1)>0):
adjDic[i].append(i-(n-1))
if (i+(n+1)<n*n):
adjDic[i].append(i+n+1)
if (i-(n+1)>=0):
adjDic[i].append(i-(n+1))
if (i+(n-1)<n*n):
adjDic[i].append(i+(n-1))

# print(adjDic)
for i in adjDic:
print(i,":",adjDic[i])
# stack=[0]
visited=set()
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node,end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

print("dfs")
dfs(visited,adjDic,0)
print()


visited = [] # List for visited nodes.
queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("bfs")
bfs(visited,adjDic,0)
print('\n')

from collections import deque

def color_graph_bfs(adj_matrix, num_colors):
# Create a dictionary to store the colors assigned to each node
node_colors = {}
# Create a queue to hold the nodes to be processed
node_queue = deque()
# Start with the first node in the graph and assign it the first color
start_node = next(iter(adj_matrix.keys()))
node_colors[start_node] = 0
node_queue.append(start_node)
# Iterate over the remaining nodes using BFS
while node_queue:
current_node = node_queue.popleft()
# Get the adjacent nodes for the current node
adj_nodes = adj_matrix[current_node]
# Initialize a set to store the colors already used by the adjacent nodes
used_colors = set()
# Iterate over each adjacent node and check its color (if assigned)
for adj_node in adj_nodes:
if adj_node in node_colors:
used_colors.add(node_colors[adj_node])
else:
# Add uncolored adjacent nodes to the queue to be processed
node_queue.append(adj_node)
# Choose the first available color from the list of colors
available_colors = set(range(num_colors)) - used_colors
chosen_color = min(available_colors)
# Assign the chosen color to the current node
node_colors[current_node] = chosen_color
return node_colors



color_dict=color_graph_bfs(adjDic,4)
count=1
for i in range(len(color_dict)):
if (count%n==0):
print(color_dict[i],end="\n")
count=1
else:
print(color_dict[i],end=" ")
count+=1

def color_graph_dfs(adj_matrix, num_colors):
# Create a dictionary to store the colors assigned to each node
node_colors = {}
# Start with the first node in the graph and assign it the first color
start_node = next(iter(adj_matrix.keys()))
dfs_coloring(adj_matrix, start_node, num_colors, node_colors)
return node_colors

def dfs_coloring(adj_matrix, node, num_colors, node_colors):
# Check if all nodes have been assigned a color
if len(node_colors) == len(adj_matrix):
return True

# Get the adjacent nodes for the current node
adj_nodes = adj_matrix[node]

# Try each color for the current node
for color in range(num_colors):
# Check if the color is already used by adjacent nodes
if any(node_colors.get(adj_node) == color for adj_node in adj_nodes):
continue

# Assign the color to the current node
node_colors[node] = color

# Recursively color the adjacent nodes
all_colored = True
for adj_node in adj_nodes:
if adj_node not in node_colors:
if not dfs_coloring(adj_matrix, adj_node, num_colors, node_colors):
all_colored = False
break

# If all adjacent nodes can be colored, return True
if all_colored:
return True

# Backtrack and try a different color
del node_colors[node]

# If all colors have been tried and none work, return False
return False


print()
color_dict=color_graph_dfs(adjDic,4)
count=1
for i in range(len(color_dict)):
if (count%n==0):
print(color_dict[i],end="\n")
count=1
else:
print(color_dict[i],end=" ")
count+=1
120 changes: 120 additions & 0 deletions astaralg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# EXP3: 8 Puzzle problem using heuristic search

# * 8 puzzle is a game where we have to arrange 8 title in a sequence (1,2,3,4,5,6,7,8,blank_tite) fitted in 3*3 matrix
# * Initially title may not be in sequence so we have to check where is blank tile, and we can swap blank tile with its adjacent tile
# * After swapping is done we check have we reached our goal state if yes game end, else we continue swapping tiles
# * We can define H(Heuristic value) like=Number of tile in correct place,this will keep track of how far we are away from our goal(h=8)

class Node:
def __init__(self, data, level, fval):
# Initialize the node with the data ,level of the node and the calculated fvalue
self.data = data
self.level = level
self.fval = fval

def generate_child(self):
# Generate hild nodes from the given node by moving the blank space
# either in the four direction {up,down,left,right}
x, y = self.find(self.data, '_')
# val_list contains position values for moving the blank space in either of
# the 4 direction [up,down,left,right] respectively.
val_list = [[x, y - 1], [x, y + 1], [x - 1, y], [x + 1, y]]
children = []
for i in val_list:
child = self.shuffle(self.data, x, y, i[0], i[1])
if child is not None:
child_node = Node(child, self.level + 1, 0)
children.append(child_node)
return children

def shuffle(self, puz, x1, y1, x2, y2):
# Move the blank space in the given direction and if the position value are out
# of limits the return None
if x2 >= 0 and x2 < len(self.data) and y2 >= 0 and y2 < len(self.data):
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None

def copy(self, root):
# copy function to create a similar matrix of the given node
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp

def find(self, puz, x):
# Specifically used to find the position of the blank space
for i in range(0, len(self.data)):
for j in range(0, len(self.data)):
if puz[i][j] == x:
return i, j


class Puzzle:
def __init__(self, size):
# Initialize the puzzle size by the the specified size,open and closed lists to empty
self.n = size
self.open = []
self.closed = []

def accept(self):
# Accepts the puzzle from the user
puz = []
for i in range(0, self.n):
temp = input().split(" ")
puz.append(temp)
return puz

def f(self, start, goal):
# Heuristic function to calculate Heuristic value f(x) = h(x) + g(x)
return self.h(start.data, goal) + start.level

def h(self, start, goal):
# Calculates the difference between the given puzzles
temp = 0
for i in range(0, self.n):
for j in range(0, self.n):
if start[i][j] != goal[i][j] and start[i][j] != '_':
temp += 1
return temp

def process(self):
# Accept Start and Goal Puzzle state
print("enter the start state matrix \n")
start = self.accept()
print("enter the goal state matrix \n")
goal = self.accept()
start = Node(start, 0, 0)
start.fval = self.f(start, goal)
# put the start node in the open list
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
print("==================================================\n")
for i in cur.data:
for j in i:
print(j, end=" ")
print("")
# if the difference between current and goal node is 0 we have reached the goal node
if (self.h(cur.data, goal) == 0):
break
for i in cur.generate_child():
i.fval = self.f(i, goal)
self.open.append(i)
self.closed.append(cur)
del self.open[0]
# sort the open list based on f value
self.open.sort(key=lambda x: x.fval, reverse=False)


puz = Puzzle(int(input("Enter the size:")))
puz.process()
Loading