Loading…
Loading…
Places N queens on an N×N board so none share a row, column, or diagonal — trying columns row by row and backtracking on conflict.
Place 6 queens so none attack each other.
1boolean solve(int[] board, int row, int n) {2 if (row == n) return true; // all rows filled — solved3 for (int col = 0; col < n; col++) // try each column4 if (isSafe(board, row, col)) { // no queen attacks it5 board[row] = col; // place the queen6 if (solve(board, row+1, n)) return true; // recurse to next row7 board[row] = -1; // backtrack: remove queen8 }9 return false;10}11 12boolean isSafe(int[] board, int row, int col) { // check placed queens13 for (int r = 0; r < row; r++) {14 int c = board[r];15 if (c == col || Math.abs(c-col) == row-r) return false; // same column or diagonal16 }17 return true; // no conflicts — safe18}