Artificial Intelligence Lab Manual
Department of Computer Science and Engineering
Experiment 1: Optimal Route Finder using Graph-based Map
Course Outcome: CO-1
Python Program:
import networkx as nx
G = nx.Graph()
G.add_edges_from([('A', 'B', {'weight': 1}), ('B', 'C', {'weight': 2}), ('A', 'C', {'weight': 4})])
path = nx.dijkstra_path(G, 'A', 'C')
print("Optimal path from A to C:", path)
Experiment 2: Robot Path Planning in Grid Environment
Course Outcome: CO-1
Python Program:
from queue import PriorityQueue
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star(grid, start, goal):
rows, cols = len(grid), len(grid[0])
open_set = PriorityQueue()
open_set.put((0, start))
came_from = {}
g_score = {start: 0}
while not open_set.empty():
_, current = open_set.get()
if current == goal:
Page 1
Artificial Intelligence Lab Manual
Department of Computer Science and Engineering
path = []
while current in came_from:
path.append(current)
current = came_from[current]
return path[::-1]
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
neighbor = (current[0]+dx, current[1]+dy)
if 0 <= neighbor[0] < rows and 0 <= neighbor[1] < cols and grid[neighbor[0]][neighbor[1]] == 0:
temp_g_score = g_score[current] + 1
if neighbor not in g_score or temp_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = temp_g_score
f_score = temp_g_score + heuristic(neighbor, goal)
open_set.put((f_score, neighbor))
grid = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0]]
path = a_star(grid, (0, 0), (2, 3))
print("Path:", path)
Experiment 3: Intelligent Game-playing Agent (Tic-Tac-Toe)
Course Outcome: CO-1
Python Program:
def check_winner(board):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != ' ': return board[i][0]
if board[0][i] == board[1][i] == board[2][i] != ' ': return board[0][i]
if board[0][0] == board[1][1] == board[2][2] != ' ': return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != ' ': return board[0][2]
Page 2
Artificial Intelligence Lab Manual
Department of Computer Science and Engineering
return None
def minimax(board, depth, is_maximizing):
winner = check_winner(board)
if winner == 'X': return 1
elif winner == 'O': return -1
elif all(cell != ' ' for row in board for cell in row): return 0
if is_maximizing:
best_score = -float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, depth + 1, False)
board[i][j] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
score = minimax(board, depth + 1, True)
board[i][j] = ' '
best_score = min(score, best_score)
return best_score
Page 3
Artificial Intelligence Lab Manual
Department of Computer Science and Engineering
board = [['X', 'O', 'X'], [' ', 'O', ' '], [' ', ' ', ' ']]
print("Best score for AI (X):", minimax(board, 0, True))
Page 4