Docsity

Java Solution for the Eight Queens Problem, Lab Reports of Artificial Intelligence

Toggle sidebar
bg1
CSE3002
LAB-1
NAME: SRIHARSHITHA DEEPALA
REG NO: 19BCD7246
SLOT: L51+L52
Write a java program for 8 queens program.
Problem Statement:
The eight queens problem is the problem of placing eight queens on
an 8×8 chessboard such that none of them attack one another (no
two are in the same row, column, or diagonal).
CODE:
import java.util.Arrays;
public class Main {
final int N = 8;
void printSolution(char board[][])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j]
+ " ");
System.out.println();
}
}
boolean isSafe(char board[][], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i] == 'Q')
return false;
pf3

Partial preview of the text

Download Java Solution for the Eight Queens Problem and more Lab Reports Artificial Intelligence in PDF only on Docsity!

CSE300 2

LAB- 1

NAME: SRIHARSHITHA DEEPALA

REG NO: 19BCD

SLOT: L51+L

Write a java program for 8 queens program.

Problem Statement:

The eight queens problem is the problem of placing eight queens on

an 8×8 chessboard such that none of them attack one another (no

two are in the same row, column, or diagonal).

CODE:

import java.util.Arrays; public class Main { final int N = 8 ; void printSolution(char board[][]) { for (int i = 0 ; i < N; i++) { for (int j = 0 ; j < N; j++) System.out.print(" " + board[i][j]

  • " "); System.out.println(); } } boolean isSafe(char board[][], int row, int col) { int i, j; for (i = 0 ; i < col; i++) if (board[row][i] == 'Q') return false;

for (i = row, j = col; i >= 0 && j >= 0 ; i--, j--) if (board[i][j] == 'Q') return false; for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j] == 'Q') return false; return true; } boolean SolveNQUt(char board[][], int col) { if (col >= N) return true; for (int i = 0 ; i < N; i++) { if (isSafe(board, i, col)) { board[i][col] = 'Q'; if (SolveNQUt(board, col + 1 ) == true) return true; board[i][col] = ''; } } return false; } boolean solveNQ() { char board[][] = new char[N][N]; for (int i = 0 ; i < N; i++) { Arrays.fill(board[i], ''); } if (SolveNQUt(board, 0 ) == false) { System.out.print("Solution does not exist"); return false; } printSolution(board); return true; } public static void main(String args[])