Solved Problem
Solved Problem
In the Sudoku puzzle we need to fill in every empty box with an integer between 1 and 9 in such a way
that every number from 1 up to 9 appears once in every row, every column and every one of the small 3
by 3 boxes highlighted with thick borders.
The difficulty of this puzzle might vary. The more the difficulty level of Sudoku puzzles, the more
challenging research problem it becomes for the computational scientists. Difficult puzzles mostly have
less prescribed symbols.
The Sudoku puzzles which are published for entertainment have unique solutions. A Sudoku puzzle is
believed to be a well-formed if it has a unique solution. Another challenging research problem is to
determine how few boxes need to be filled for a Sudoku puzzle to be well-formed. Well-formed Sudoku
with 17 symbols exist. It is unknown whether or not there exists a well formed puzzle with only 16 clues.
In this method for solving the sudoku puzzle, first we assign the size of the 2D matrix to variable M
(M*M).
If we find same num in the same row or same column or in the specific 3*3 matrix, ‘false’ will be
returned.
Then we will check if we have reached the 8th row and 9th column and return true for stopping the
further backtracking.
Next we will check if the column value becomes 9 then we move to the next row and column.
Further now we see if the current position of the grid has value greater than 0, then we iterate for next
column.
After checking if it is a safe place , we move to the next column and then assign num in current (row ,col)
position of the grid. Later we check for next possibility with next column.
As our assumption was wrong, we discard the assigned num and then we go for the next assumption
with different num value
Implementing the sudoku solver in Python
We’ll use the backtracking method to create our sudoku solver in Python. Backtracking means switching
back to the previous step as soon as we determine that our current solution cannot be continued into a
complete one. We use this principle of backtracking to implement the sudoku algorithm.
Program :
M=9
def puzzle(a):
for i in range(M):
for j in range(M):
print()
for x in range(9):
if grid[row][x] == num:
return False
for x in range(9):
if grid[x][col] == num:
return False
for i in range(3):
for j in range(3):
return False
return True
return True
if col == M:
row += 1
col = 0
if grid[row][col] > 0:
grid[row][col] = num
return True
grid[row][col] = 0
return False
[0, 1, 0, 0, 0, 4, 0, 0, 0],
[4, 0, 7, 0, 0, 0, 2, 0, 8],
[0, 0, 5, 2, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 9, 8, 1, 0, 0],
[0, 4, 0, 0, 0, 3, 0, 0, 0],
[0, 0, 0, 3, 6, 0, 0, 7, 2],
[0, 7, 0, 0, 0, 0, 0, 0, 3],
[9, 0, 3, 0, 0, 0, 6, 0, 4]]
if (Suduko(grid, 0, 0)):
puzzle(grid)
else:
Solution :
258736941
619824357
437915268
395271486
762498135
841653729
184369572
576142893
923587614
You can import the sudoku py-sudoku.PyPI module from https://pypi.org/project/py-sudoku/.
Graph coloring (also called vertex coloring) is a way of coloring a graph’s vertices such that no two
adjacent vertices share the same color. This post will discuss a greedy algorithm for graph coloring and
minimize the total number of colors used.
Program :
class Graph:
# Constructor
self.adj[src].append(dest)
self.adj[dest].append(src)
def colorGraph(graph):
result = {}
for u in range(N):
color = 1
for c in assigned:
if color != c:
break
color = color + 1
for v in range(N):
if __name__ == '__main__':
edges = [(0, 1), (0, 4), (0, 5), (4, 5), (1, 4), (1, 3), (2, 3), (2, 4)]
N=6
graph = Graph(edges, N)
colorGraph(graph)
Solution :
[Program finished]
Breadth-First Search (BFS) is an algorithm used for traversing graphs or trees. Traversing means visiting
each node of the graph. Breadth-First Search is a recursive algorithm to search all the vertices of a graph
or a tree. BFS in python can be implemented by using data structures like a dictionary and lists. Breadth-
First Search in tree and graph is almost the same. The only difference is that the graph may contain
cycles, so we may traverse to the same node again.
As breadth-first search is the process of traversing each node of the graph, a standard BFS algorithm
traverses each vertex of the graph into two parts: 1) Visited 2) Not Visited. So, the purpose of the
algorithm is to visit all the vertex while avoiding cycles.
Now, we will see how the source code of the program for implementing breadth first search in python.
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
Solution :
537248
[Program finished]
In the above code, first, we will create the graph for which we will use the breadth-first search. After
creation, we will create two lists, one to store the visited node of the graph and another one for storing
the nodes in the queue.
After the above process, we will declare a function with the parameters as visited nodes, the graph itself
and the node respectively. And inside a function, we will keep appending the visited and queue lists.
Then we will run the while loop for the queue for visiting the nodes and then will remove the same node
and print it as it is visited.
At last, we will run the for loop to check the not visited nodes and then append the same from the
visited and queue list.As the driver code, we will call the user to define the bfs function with the first
node we wish to visit..
Depth First Search (DFS)
Depth first Search or Depth first traversal is a recursive algorithm for searching all the vertices of a graph
or tree data structure. Traversal means visiting all the nodes of a graph.
Depth First Search algorithm works with an example. We use an undirected graph with 5 vertices.
A standard DFS implementation puts each vertex of the graph into one of two categories:
1) Visited
2) Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its
adjacent vertices in the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already
been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed
the Depth First Traversal of the graph.
The pseudocode for DFS is shown below. In the init() function, notice that we run the DFS function on
every node. This is because the graph might have two different disconnected parts so to make sure that
we cover every vertex, we can also run the DFS algorithm on every node.
DFS algorithm in Python
# DFS algorithm
if visited is None:
visited = set()
visited.add(start)
print(start)
return visited
'2': set(['0']),
'3': set(['1']),
Output :
0
[Program finished]
# adjacent nodes.
# 3) Repeat until all the nodes are visited, or the node to be
# searched is found.
Program :
graph = {
'A' : ['B','C'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
##################
print (node)
visited.add(node)
Output :
[Program finished]
IDDFS combines depth-first search’s space-efficiency and breadth-first search’s fast search (for nodes
closer to root).
IDDFS calls DFS for different depths starting from an initial value. In every call, DFS is restricted from
going beyond given depth. So basically we do DFS in a BFS fashion.
# given graph
# list representation
class Graph:
def __init__(self,vertices):
# No. of vertices
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DLS(self,src,target,maxDepth):
for i in self.graph[src]:
if(self.DLS(i,target,maxDepth-1)):
return True
return False
# maximum depth
for i in range(maxDepth):
return True
return False
g = Graph (7);
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(1, 4)
g.addEdge(2, 5)
g.addEdge(2, 6)
else :
print ("Target is NOT reachable from source " + "within max depth"Target is reachable from source
within max depth
[Program finished]
Output :
[Program finished]