Skip to content

Commit 5a01b18

Browse files
maze solver
1 parent 2196f7c commit 5a01b18

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Coding/Java/Maze.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.util.Scanner;
2+
3+
public class Maze {
4+
public static void main(String[] args) {
5+
Scanner sc = new Scanner(System.in);
6+
System.out.println("Enter the value of n: ");
7+
int n = sc.nextInt();
8+
boolean[][] board = new boolean[n][n];
9+
System.out.println(nQueens(board,0));
10+
}
11+
static int nQueens(boolean[][] board, int row){
12+
if(row==board.length){
13+
display(board);
14+
System.out.println();
15+
return 1;
16+
}
17+
int count = 0;
18+
for(int col =0;col<board.length;col++){
19+
if(isSafe(board, row, col)){
20+
board[row][col] = true;
21+
count += nQueens(board,row+1);
22+
board[row][col] = false;
23+
}
24+
}
25+
return count;
26+
}
27+
28+
static boolean isSafe(boolean[][] board, int row, int col){
29+
30+
for(int i=0;i<row;i++){
31+
if(board[i][col]) {
32+
return false;
33+
}
34+
}
35+
36+
int maxLeft = Math.min(row,col);
37+
38+
for(int i=1;i<=maxLeft;i++){
39+
if(board[row-i][col-i]){
40+
return false;
41+
}
42+
}
43+
44+
int maxRight = Math.min(row, board.length - col - 1);
45+
46+
for(int i=1;i<=maxRight;i++){
47+
if(board[row-i][col+i]){
48+
return false;
49+
}
50+
}
51+
52+
return true;
53+
}
54+
static void display(boolean[][] board){
55+
for(boolean[] row : board){
56+
for(boolean element : row){
57+
if(element){
58+
System.out.print("Q ");
59+
}
60+
else{
61+
System.out.print("X ");
62+
}
63+
}
64+
System.out.println();
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)