forked from krimanisha/Hacktoberfest21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens.java
56 lines (56 loc) · 1.54 KB
/
N-Queens.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
public class NQueens
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of n");
int n=sc.nextInt();
char board[][]=new char[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
board[i][j]='-';
if(solveNQueens(board,0,n)) solution(board,n);
else System.out.println("No solution exists");
}
public static void solution(char board[][], int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(" "+board[i][j]+" ");
System.out.println();
}
}
public static boolean isSafe(char board[][], int row, int column, int n)
{
int i,j;
for(i=0;i<column;i++)
{
if(board[row][i]=='Q') return false;
}
for(i=row,j=column; i>=0 && j>=0;i--,j--)
{
if(board[i][j]=='Q') return false;
}
for(i=row,j=column; i<n && j>=0;i++,j--)
{
if(board[i][j]=='Q') return false;
}
return true;
}
public static boolean solveNQueens(char board[][], int column, int n)
{
if(column>=n) return true;
for(int i=0;i<n;i++)
{
if(isSafe(board,i,column,n))
{
board[i][column]='Q';
if(solveNQueens(board, column+1,n)) return true;
board[i][column]='-';
}
}
return false;
}
}