File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
CodingBlocks Training/Day12 Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ package Lecture12 ;
2+
3+ public class NQueen {
4+
5+ public static void main (String [] args ) {
6+
7+ int N = 4 ;
8+ boolean [][] board = new boolean [N ][N ];
9+ int row = 0 ;
10+ System .out .println (countNQueens (board , row )); // 2
11+ }
12+
13+ public static int countNQueens (boolean [][] board , int row ) {
14+ if (row == board .length ) {
15+ return 1 ;
16+ }
17+
18+ int count = 0 ;
19+ for (int col = 0 ; col < board .length ; col ++) {
20+ if (isSafePosition (board , row , col )) {
21+ board [row ][col ] = true ;
22+ count = count + countNQueens (board , row + 1 );
23+ board [row ][col ] = false ;
24+ }
25+ }
26+ return count ;
27+ }
28+
29+ public static boolean isSafePosition (boolean [][] board , int row , int col ) {
30+ // checking column
31+ for (int i = row ; i >= 0 ; i --) {
32+ if (board [i ][col ]) {
33+ return false ;
34+ }
35+ }
36+
37+ // checking left diagonal
38+ for (int i = row , j = col ; i >= 0 && j >= 0 ; i --, j --) {
39+ if (board [i ][j ]) {
40+ return false ;
41+ }
42+ }
43+
44+ // checking right diagonal
45+ for (int i = row , j = col ; i >= 0 && j < board .length ; i --, j ++) {
46+ if (board [i ][j ]) {
47+ return false ;
48+ }
49+ }
50+
51+ return true ;
52+ }
53+
54+ /*
55+ public static void display(boolean[][] board) {
56+ for (int row = 0; row < board.length; row++) {
57+ for (int col = 0; col < board[row].length; col++) {
58+ System.out.print(board[row][col] + " ");
59+ }
60+ System.out.println();
61+ }
62+ }
63+ */
64+
65+ }
You can’t perform that action at this time.
0 commit comments