8 Puzzle
8 Puzzle
Introduction:
Source Code:
ids :-
start(State),
length(Moves, N),
show([start|Moves], Path),
goal(State), !,
reverse([State|States], Path).
not(memberchk(Next, [State|States])),
show([], _).
show([Move|Moves], [State|States]) :-
State = state(A,B,C,D,E,F,G,H,I),
format('~n~w~n~n', [Move]),
format('~w ~w ~w~n',[A,B,C]),
format('~w ~w ~w~n',[D,E,F]),
format('~w ~w ~w~n',[G,H,I]),
show(Moves, States).
start( state(6,1,3,4,*,5,7,2,0) ).
goal( state(*,0,1,2,3,4,5,6,7) ).
Output:
Time(ids)
Write a python program to implement Breadth First Search Traversal?
Introduction:
Breadth-first search (BFS) is an algorithm for traversing graphs or trees. Breath-first searches for
trees and graphs are almost the same. The only difference is that the graph may contain cycles,
so we may traverse to the same node again. To avoid processing the same node again, we use the
boolean visited array, which will mark the visited vertices. BFS uses a queue data structure for
finding the shortest path in a graph.
The breadth-first search algorithm uses a queue and a visited array. We use the queue to get the
next vertex to start the search, and the visited array is used to mark all the nodes that have been
visited, so when it appears again, we will perform BFS on that node.
Create a queue and insert any one vertex of the graph at the back of the queue.
Initialize a visited array and mark that vertex as visited.
Follow the below process till the queue becomes empty:
o Remove a front vertex from the queue.
o Get all the adjacent vertices of the removed vertex.
o If the adjacent vertex has not been visited, mark it as visited and insert it at the
back of the queue.
Let’s have a look at the algorithm with an example. Here we have an undirected graph of 5
vertices.
Now, we can see that there are 3 neighbors of node A that are unvisited, so alphabetically we
use node B and mark it as visited, and add it to the queue.
Next, the unvisited node is C, so mark it as visited and add it to the queue.
Now, the node D remains, so mark it as visited and add it to the queue.
Now, node A is left with no unvisited nodes, so start removing nodes from the queue. So node B
pops from the queue, and since B has only one neighbor, i.e., A, and it has already been visited,
we move forward and pop the next node from the queue.
Node C is removed from the queue. C has two neighbors: A and D. They have already been
visited.
Now, only D remains in the queue, so pop it from the queue and mark all its neighbors visited.
So D has 3 neighbors: A, C, and E. But only E is not visited, so mark E as visited and add E to
the queue.
At last, pop E from the queue, and mark it as visited, since E has only one neighbor, i.e., D, but it
has already been visited. So our queue will become empty.
Now, our queue becomes empty, so we have completed the breadth-first search traversal of the
graph.
Source code:
# Create a graph given in the above diagram.
graph = {
'B': ['A'],
'E': ['D'],
def bfs(node):
queue = []
visited.append(node)
queue.append(node)
while queue:
# Remove the front vertex or the vertex at the 0th index from the queue and print that vertex.
v = queue.pop(0)
print(v, end=" ")
# Get all adjacent nodes of the removed node v from the graph hash table.
visited.append(neigh)
queue.append(neigh)
# Driver Code
if __name__ == "__main__":
bfs('A')
Write a python program to implement Depth First Search Traversal?
Introduction:
Depth-first search (DFS), is an algorithm for tree traversal on graph or tree data structures. It
can be implemented easily using recursion and data structures like dictionaries and sets.
The Algorithm
1. Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.
2. Repeat until all the nodes are visited, or the node to be searched is found.
Implementation
Source code:
# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
# Driver Code
dfs(visited, graph, 'A')
Write a python program to implement Water Jug Problem
Example
Input: 3, 5, 4
Output: 6
Explanation: The following steps are taken:
1. Fill the m liter jug and empty it into the n liter jug.
2. When the m liter jug becomes empty refill it.
3. When the n-liter jug becomes full, empty it.
4. Repeat the above steps till any one of the jugs contains the required amount of water in
them.
Method 02) Always pour from 2nd jug to 1st jug
1. Fill the n-liter jug and empty it into the m-liter jug.
2. When the n liter jug becomes empty refill it.
3. When the m liter jug becomes full, empty it.
4. Repeat the above steps till any of the jugs contain the required amount of water in them.
Source code:
from collections import deque
def Solution(a, b, target):
m = {}
isSolvable = False
path = []
q = deque()
# Current state
u = q.popleft()
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
path.append([u[0], u[1]])
m[(u[0], u[1])] = 1
if (u[0] == target):
if (u[1] != 0):
path.append([u[0], 0])
else:
if (u[0] != 0):
path.append([0, u[1]])
sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break
c = u[0] - ap
d = u[1] + ap
q.append([a, 0])
q.append([0, b])
if (not isSolvable):
print("Solution not possible")
if __name__ == '__main__':
Introduction
In this article, I am showing you how to create a very simple game of Tic-Tac-Toe in Python.
Tic-Tac-Toe is a very simple two-player game. So only two players can play at a time. This
game is also known as Noughts and Crosses or Xs and Os game. One player plays with X, and
the other player plays with O. In this game, we have a board consisting of a 3X3 grid. The
number of grids may be increased.
Whoever places three respective marks (X or O) horizontally, vertically, or diagonally will be the
winner.
Source Code:
import os
import time
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1
# Win Flags
Win = 1
Draw = -1
Running = 0
Stop = 1
Game = Running
Mark = 'X'
def DrawBoard():
print(" %c | %c | %c " % (board[1], board[2], board[3]))
print("___|___|___")
print(" %c | %c | %c " % (board[4], board[5], board[6]))
print("___|___|___")
print(" %c | %c | %c " % (board[7], board[8], board[9]))
print(" | | ")
def CheckPosition(x):
if board[x] == ' ':
return True
else:
return False
def CheckWin():
global Game
if player % 2 != 0:
print("Player 1's chance")
Mark = 'X'
else:
print("Player 2's chance")
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark: "))
if CheckPosition(choice):
board[choice] = Mark
player += 1
CheckWin()
os.system('cls')
DrawBoard()
if Game == Draw:
print("Game Draw")
elif Game == Win:
player -= 1
if player % 2 != 0:
print("Player 1 Won")
else:
print("Player 2 Won")