0% found this document useful (0 votes)
10 views35 pages

Ai Lab

The document describes an algorithm to solve the N queens problem using backtracking. It defines a Node class to represent positions on the chessboard and uses a priority queue to implement A* search. The algorithm returns the optimal path between a start and target node by traversing the parent pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views35 pages

Ai Lab

The document describes an algorithm to solve the N queens problem using backtracking. It defines a Node class to represent positions on the chessboard and uses a priority queue to implement A* search. The algorithm returns the optimal path between a start and target node by traversing the parent pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

PROGRAM

import java.util.Scanner;

public class hillClimbing {

public static void main(String[] args) {

int n,i,j;

Scanner sc=new Scanner(System.in);

System.out.println("Enter number of nodes in graph");

n=sc.nextInt();

int[][] graph=new int[n][n];

for(i=0;i<n;i++)

for(j=0;j<n;j++)

graph[i][j]=0;

for(i=0;i<n;i++)

for(j=i+1;j<n;j++)

System.out.println("Is "+i+" is connected to "+ j);

graph[i][j]=sc.nextInt();

System.out.println("The adjacency matrix is:");

for(i=0;i<n;i++)

for(j=0;j<n;j++)

{ System.out.print(graph[i][j]+ "\t");

}
System.out.println();

}}}

OUTPUT
PROGRAM
import java.io.*;
import java.util.*;

public class Node implements Comparable<Node> {


// Id for readability of result purposes
private static int idCounter = 0;
public int id;

// Parent in the path


public Node parent = null;

public List<Edge> neighbors;

// Evaluation functions
public double f = Double.MAX_VALUE;
public double g = Double.MAX_VALUE;
// Hardcoded heuristic
public double h;

Node(double h){
this.h = h;
this.id = idCounter++;
this.neighbors = new ArrayList<>();
}

@Override
public int compareTo(Node n) {
return Double.compare(this.f, n.f);
}
public static class Edge {
Edge(int weight, Node node){
this.weight = weight;
this.node = node;
}

public int weight;


public Node node;
}

public void addBranch(int weight, Node node){


Edge newEdge = new Edge(weight, node);
neighbors.add(newEdge);
}

public double calculateHeuristic(Node target){


return this.h;
}
public static Node aStar(Node start, Node target){
PriorityQueue<Node> closedList = new PriorityQueue<>();
PriorityQueue<Node> openList = new PriorityQueue<>();

start.f = start.g + start.calculateHeuristic(target);


openList.add(start);

while(!openList.isEmpty()){
Node n = openList.peek();
if(n == target){
return n;
}
for(Node.Edge edge : n.neighbors){
Node m = edge.node;
double totalWeight = n.g + edge.weight;

if(!openList.contains(m) && !closedList.contains(m)){


m.parent = n;
m.g = totalWeight;
m.f = m.g + m.calculateHeuristic(target);
openList.add(m);
} else {
if(totalWeight < m.g){
m.parent = n;
m.g = totalWeight;
m.f = m.g + m.calculateHeuristic(target);

if(closedList.contains(m)){
closedList.remove(m);
openList.add(m);
}
}
}
}

openList.remove(n);
closedList.add(n);
}
return null;
}
public static void printPath(Node target){
Node n = target;

if(n==null)
return;

List<Integer> ids = new ArrayList<>();

while(n.parent != null){
ids.add(n.id);
n = n.parent;
}
ids.add(n.id);
Collections.reverse(ids);

for(int id : ids){
System.out.print(id + " ");
}
System.out.println("");
}
public static void main(String[] args) {
Node head = new Node(3);
head.g = 0;

Node n1 = new Node(2);


Node n2 = new Node(2);
Node n3 = new Node(2);

head.addBranch(1, n1);
head.addBranch(5, n2);
head.addBranch(2, n3);
n3.addBranch(1, n2);

Node n4 = new Node(1);


Node n5 = new Node(1);
Node target = new Node(0);

n1.addBranch(7,n4);
n2.addBranch(4, n5);
n3.addBranch(6, n4);

n4.addBranch(3, target);
n5.addBranch(1, n4);
n5.addBranch(3, target);
Node res = aStar(head, target);
printPath(res);
}
}

OUTPUT
PROGRAM
import java.util.Scanner;

public class tic_tac_toe {

private static final char EMPTY = ' ';

private static final char PLAYER_X = 'X';

private static final char PLAYER_O = 'O';

private static final char[][] BOARD = new char[3][3];

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {

initializeBoard();

char currentPlayer = PLAYER_X;

boolean gameFinished = false;

while (!gameFinished) {

displayBoard();

playerMove(currentPlayer);

gameFinished = checkWin(currentPlayer) || checkDraw();

currentPlayer = (currentPlayer == PLAYER_X) ? PLAYER_O : PLAYER_X;

displayBoard();

printResult();

scanner.close();

static void initializeBoard() {

for (char[] row : BOARD) {

for (int j = 0; j < row.length; j++) {

row[j] = EMPTY;

}
}

static void displayBoard() {

System.out.println(" -------------");

for (char[] row : BOARD) {

System.out.print("| ");

for (char cell : row) {

System.out.print(cell + " | ");

System.out.println("\n ------------- ");

static void playerMove(char player) {

int row, col;

do {

System.out.println("Player " + player + ", enter your move (row[1-3] column[1-3]):


");

row = scanner.nextInt() - 1;

col = scanner.nextInt() - 1;

} while (!isValidMove(row, col));

BOARD[row][col] = player;

static boolean isValidMove(int row, int col) {

return row >= 0 && row < 3 && col >= 0 && col < 3 && BOARD[row][col] ==
EMPTY;

static boolean checkWin(char player) {

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


if (BOARD[i][0] == player && BOARD[i][1] == player && BOARD[i][2] == player
||

BOARD[0][i] == player && BOARD[1][i] == player && BOARD[2][i] ==


player) {

return true; // Row or Column win

return BOARD[0][0] == player && BOARD[1][1] == player && BOARD[2][2] ==


player ||

BOARD[0][2] == player && BOARD[1][1] == player && BOARD[2][0] ==


player; // Diagonal win

static boolean checkDraw() {

for (char[] row : BOARD) {

for (char cell : row) {

if (cell == EMPTY) {

return false;

return true; // Board full, game draw

static void printResult() {

if (checkWin(PLAYER_X)) {

System.out.println("Player X wins!");

} else if (checkWin(PLAYER_O)) {

System.out.println("Player O wins!");

} else {
System.out.println("It's a draw!"); }}}

OUTPUT
PROGRAM

import java.util.LinkedList;

import java.util.Queue;

public class snakeandladder {

// An entry in queue used in BFS

static class qentry {

int v; // Vertex number

int dist; // Distance of this vertex from source

static int getMinDiceThrows(int move[], int n)

int visited[] = new int[n];

Queue<qentry> q = new LinkedList<>();

qentry qe = new qentry();

qe.v = 0;

qe.dist = 0;

// Mark the node 0 as visited and enqueue it.

visited[0] = 1;

q.add(qe);

// Do a BFS starting from vertex at index 0

while (!q.isEmpty()) {

qe = q.remove();

int v = qe.v;

if (v == n - 1)

break;

for (int j = v + 1; j <= (v + 6) && j < n;

++j) {
if (visited[j] == 0) {

qentry a = new qentry();

a.dist = (qe.dist + 1);

visited[j] = 1;

if (move[j] != -1)

a.v = move[j];

else

a.v = j;

q.add(a);

return qe.dist;

public static void main(String[] args)

int N = 30;

int moves[] = new int[N];

for (int i = 0; i < N; i++)

moves[i] = -1;

// Ladders

moves[2] = 21;

moves[4] = 7;

moves[10] = 25;

moves[19] = 28;

// Snakes

moves[26] = 0;
moves[20] = 8;

moves[16] = 3;

moves[18] = 6;

System.out.println("Min Dice throws required is "

+ getMinDiceThrows(moves, N));

OUTPUT
PROGRAM

import java.util.Random;

import java.util.Scanner;

public class stonepaper {

private static final String[] MOVES = {"rock", "paper", "scissors"};

private static final Random random = new Random();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("How many rounds of Rock-Paper-Scissors would you like to


play?");

int rounds = Integer.parseInt(scanner.nextLine());

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

playRockPaperScissors(scanner);

static void playRockPaperScissors(Scanner scanner) {

System.out.println("Make a move! (rock/paper/scissors)");

String playerMove = scanner.nextLine();

String computerMove = MOVES[random.nextInt(MOVES.length)];

System.out.println("Computer chose " + computerMove + "!");

if (playerMove.equals(computerMove)) {

System.out.println("It's a draw!");

} else if (playerWins(playerMove, computerMove)) {

System.out.println("Player wins!");

} else {

System.out.println("Computer wins!");
}

static boolean playerWins(String playerMove, String computerMove) {

return (playerMove.equals("rock") && computerMove.equals("scissors")) ||

(playerMove.equals("paper") && computerMove.equals("rock")) ||

(playerMove.equals("scissors") && computerMove.equals("paper"));

OUTPUT
PROGRAM
import java.io.*;
import java.util.*;
public class N_queens {
void printSolution(int board[][], int N)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1)
System.out.print("Q ");
else
System.out.print(". ");
}
System.out.println();
}
}
boolean isSafe(int board[][], int row, int col, int N)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
boolean solveNQUtil(int board[][], int col, int N)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col, N)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1, N) == true)
return true;
board[i][col] = 0; // BACKTRACK
}
}
return false;
}
boolean solveNQ(int N)
{
int board[][] = new int[N][N];
for(int i = 0; i< N ; i++){
for(int j = 0; j < N ; j++)
board[i][j] = 0;
}
if (solveNQUtil(board, 0 , N) == false) {
System.out.print("Solution does not exist");
return false;
}
printSolution(board,N);
return true;
}
public static void main(String args[])
{
N_queens Queen = new N_queens();
Scanner in = new Scanner(System.in);
System.out.println("Enter the no of queens : ");
int n = in.nextInt();
Queen.solveNQ(n);
}
}

OUTPUT
PROGRAM
import java.util.*;
import java.io.*;
import java.util.Scanner;
class TSP
{
static int findHamiltonianCycle(int[][] distance, boolean[] visitCity, int currPos, int cities,
int count, int cost, int hamiltonianCycle)
{

if (count == cities && distance[currPos][0] > 0)


{
hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]);
return hamiltonianCycle;
}
for (int i = 0; i < cities; i++)
{
if (visitCity[i] == false && distance[currPos][i] > 0)
{
visitCity[i] = true;
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, cities, count + 1,
cost + distance[currPos][i], hamiltonianCycle);
visitCity[i] = false;
}
}
return hamiltonianCycle;
}
public static void main(String[] args)
{
int cities;
Scanner sc = new Scanner(System.in);
System.out.println("Enter total number of cities ");
cities = sc.nextInt();
int distance[][] = new int[cities][cities];
for( int i = 0; i < cities; i++){
for( int j = 0; j < cities; j++){
System.out.println("Distance from city"+ (i+1) +" to city"+ (j+1) +": ");
distance[i][j] = sc.nextInt();
}
}
boolean[] visitCity = new boolean[cities];
visitCity[0] = true;
int hamiltonianCycle = Integer.MAX_VALUE;
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, 0, cities, 1, 0,
hamiltonianCycle);
System.out.println("Shortest path that visit all nodes is "+hamiltonianCycle);
}
}
OUTPUT

You might also like