You are on page 1of 14

AI - DIGITAL ASSIGNMENT

Tummala Rohith

21BBS0134

1.)N Queens using backtracking:

Code:

N=4

def print_solution(board):

for i in range(N):

for j in range(N):

print(board[i][j], end=' ')

print()

def is_safe(board, row, col):

# Check this row on the left side

for i in range(col):

if board[row][i] == 1:

return False

# Check upper diagonal on the 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 the 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_n_queens_util(board, col):

# Base case: If all queens are placed, then return True

if col >= N:

return True

# Consider this column and try placing a queen in all rows one by one

for i in range(N):

if is_safe(board, i, col):

# Place the queen in board[i][col]

board[i][col] = 1

# Recur to place the rest of the queens

if solve_n_queens_util(board, col + 1):

return True

# If placing the queen in board[i][col] doesn't lead to a solution, backtrack and remove the queen

board[i][col] = 0

# If the queen cannot be placed in any row in this column col, then return False

return False

def solve_n_queens():

board = [[0] * N for _ in range(N)]

if solve_n_queens_util(board, 0) == False:

print("Solution does not exist")


return False

print_solution(board)

return True

# Driver program to test the above function

print("Tummala Rohith")

print("21BBS0134")

solve_n_queens()

3.)AIM: TSP using BSF Problem

Code:

# Python program to solve Travelling Salesman

# Problem using bfs

from collections import deque

def tsp_bfs(graph, start):

def calculate_distance(path):

"""

Calculate the total distance of a given path.

"""

distance = 0

for i in range(len(path) - 1):

distance += graph[path[i]][path[i + 1]]

return distance

cities = list(graph.keys())
cities.remove(start)

shortest_path = None

shortest_distance = float('inf')

queue = deque([(start, [start])])

while queue:

current_city, path = queue.popleft()

if len(path) == len(graph):

distance = calculate_distance(path +

[start])

if distance < shortest_distance:

shortest_distance = distance

shortest_path = path + [start]

for neighbor in cities:

if neighbor not in path:

queue.append((neighbor, path +

[neighbor]))

return shortest_path, shortest_distance

graph = {

'A': {'B': 10, 'C': 15, 'D': 20},

'B': {'A': 10, 'C': 35, 'D': 25},

'C': {'A': 15, 'B': 35, 'D': 30},

'D': {'A': 20, 'B': 25, 'C': 30}

start_city = 'A'

shortest_path, shortest_distance = tsp_bfs(graph,

start_city)

print("Rohith 21BBS0134")

print("Shortest path:", shortest_path)

print("Shortest distance:", shortest_distance)


4.) Calculate the heuristic (Manhattan distance)

import heapq

# Function to calculate the heuristic (Manhattan distance)

def calculate_heuristic(state, goal_state):

heuristic = 0

for i in range(3):

for j in range(3):

if state[i][j] != goal_state[i][j]:

x, y = divmod(goal_state[i][j] - 1, 3)

heuristic += abs(x - i) + abs(y - j)

return heuristic

# Function to find the possible moves from the current state

def find_possible_moves(state):

possible_moves = []

for i in range(3):

for j in range(3):

if state[i][j] == 0:

if i > 0:

possible_moves.append((i - 1, j)) # Move Up

if i < 2:

possible_moves.append((i + 1, j)) # Move Down

if j > 0:

possible_moves.append((i, j - 1)) # Move Left


if j < 2:

possible_moves.append((i, j + 1)) # Move Right

return possible_moves

# Function to swap tiles and create a new state

def swap_tiles(state, move):

new_state = [list(row) for row in state]

i, j = move[0], move[1]

x, y = get_zero_position(new_state)

new_state[x][y], new_state[i][j] = new_state[i][j], new_state[x][y]

return tuple(tuple(row) for row in new_state)

# Function to get the position of the blank (0) tile

def get_zero_position(state):

for i in range(3):

for j in range(3):

if state[i][j] == 0:

return i, j

# A* algorithm implementation

def solve_8_puzzle(initial_state, goal_state):

open_list = []

heapq.heapify(open_list)

heapq.heappush(open_list, (0, initial_state))

visited_states = set()

g_scores = {initial_state: 0}

parents = {initial_state: None}

while open_list:
current_state = heapq.heappop(open_list)[1]

if current_state == goal_state:

path = []

while current_state:

path.append(current_state)

current_state = parents[current_state]

return path[::-1]

visited_states.add(current_state)

possible_moves = find_possible_moves(current_state)

for move in possible_moves:

new_state = swap_tiles(current_state, move)

g_score = g_scores[current_state] + 1

if new_state not in visited_states or g_score < g_scores[new_state]:

g_scores[new_state] = g_score

f_score = g_score + calculate_heuristic(new_state, goal_state)

heapq.heappush(open_list, (f_score, new_state))

parents[new_state] = current_state

return None

# Test case

initial_state = ((1, 2, 3), (4, 5, 6), (0, 7, 8))

goal_state = ((1, 2, 3), (4, 5, 6), (7, 8, 0))

print("Rohith 21BBS0134")
solution = solve_8_puzzle(initial_state, goal_state)

if solution:

print("Solution Found!")

for state in solution:

print(state)

else:

print("No solution found.")

5.)Aim: TSP using A* search:

Code:

import heapq

def tsp(graph, start):

# Define the heuristic function (estimated cost to reach the goal)

def heuristic(node):

# In this example, we use a simple minimum spanning tree as the heuristic

# You can modify this function to use a different heuristic for better performance

mst_cost = minimum_spanning_tree(graph)

return mst_cost[node]

# Define the function to calculate the minimum spanning tree


def minimum_spanning_tree(graph):

mst = {}

queue = []

heapq.heappush(queue, (0, start))

while queue:

cost, node = heapq.heappop(queue)

if node in mst:

continue

mst[node] = cost

for neighbor, edge_cost in graph[node].items():

if neighbor not in mst:

heapq.heappush(queue, (edge_cost, neighbor))

return mst

# A* algorithm

open_set = [(0, start, frozenset([start]))]

while open_set:

cost, current, path = heapq.heappop(open_set)

if len(path) == len(graph):

return list(path) # Return the optimal path

for neighbor, edge_cost in graph[current].items():

if neighbor not in path:

g = cost + edge_cost

h = heuristic(neighbor)
f=g+h

heapq.heappush(open_set, (f, neighbor, path.union([neighbor])))

return None # No feasible path found

# Example usage

graph = {

'A': {'B': 10, 'C': 15, 'D': 20},

'B': {'A': 10, 'C': 35, 'D': 25},

'C': {'A': 15, 'B': 35, 'D': 30},

'D': {'A': 20, 'B': 25, 'C': 30}

start_node = 'A'

optimal_path = tsp(graph, start_node)

print("Tummala Rohith")

print("21BBS0134")

print("Optimal Path:", optimal_path)

1.) AIM: TRAVELLING SALESMAN PROBLEM

Code:

#include <iostream>
#include <vector>

#include <climits>

std::vector<std::vector<int>> getGraph(int nodes, int edges) {

std::vector<std::vector<int>> adj(nodes, std::vector<int>(nodes, 0));

for (int i = 0; i < edges; i++) {

int n1, n2, weight;

std::cout << "Edge between nodes (n1, n2) & weight: ";

std::cin >> n1 >> n2 >> weight;

adj[n1 - 1][n2 - 1] = weight;

adj[n2 - 1][n1 - 1] = weight;

return adj;

void printGraph(const std::vector<std::vector<int>>& graph, int nodes) {

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

std::cout << graph[i][j] << " ";

std::cout << std::endl;

void TSP(const std::vector<std::vector<int>>& graph, int num) {

int source = 0;
std::vector<int> nodes;

for (int i = 0; i < num; i++) {

if (i != source) nodes.push_back(i);

std::vector<int> path = {source};

// Iterate over all unvisited nodes.

for (int i = 0; i < nodes.size(); i++) {

// Find the nearest unvisited node.

int nearest = -1;

int minDist = INT_MAX;

for (int j = 0; j < nodes.size(); j++) {

if (nodes[j] != path.back() && graph[path.back()][nodes[j]] < minDist) {

// If the node is unvisited and the distance to the node is less than the minimum distance,

// then the node is the nearest unvisited node.

minDist = graph[path.back()][nodes[j]];

nearest = nodes[j];

// Add the nearest node to the path.

path.push_back(nearest);

int cost = 0;
// Print the path.

std::cout << "The minimum path is: ";

for (int i = 0; i < path.size() - 1; i++) {

std::cout << path[i] + 1 << " ";

cost += graph[path[i]][path[i + 1]];

std::cout << std::endl;

std::cout << "The cost of the path is: " << cost << std::endl;

int main() {

int nodes, edges;

std::cin >> nodes >> edges;

std::vector<std::vector<int>> graph = getGraph(nodes, edges);

std::cout << "The Adjacency matrix is: " << std::endl;

printGraph(graph, nodes);

TSP(graph, nodes);

std::cout << "Tummala Rohith 21BBS0134";

return 0;

}
1.) AIM: A* PROBLEM:

Code:

You might also like