|
| 1 | +--- |
| 2 | +id: n-queens |
| 3 | +title: N-Queens (LeetCode) |
| 4 | +sidebar_label: 0051-N-Queens |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Backtracking |
| 8 | +description: "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other." |
| 9 | +--- |
| 10 | + |
| 11 | +## Problem Description |
| 12 | + |
| 13 | +| Problem Statement | Solution Link | LeetCode Profile | |
| 14 | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | |
| 15 | +| [N-Queen](https://leetcode.com/problems/n-queens/) | [N-Queen](https://leetcode.com/problems/n-queens/) | [DaminiChachane](https://leetcode.com/u/divcxl15/) | |
| 16 | + |
| 17 | +### Problem Description |
| 18 | + |
| 19 | +The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. |
| 20 | + |
| 21 | +Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. |
| 22 | + |
| 23 | +Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. |
| 24 | + |
| 25 | + |
| 26 | +### Examples |
| 27 | + |
| 28 | +#### Example 1 |
| 29 | + |
| 30 | +- **Input:** `n = 4` |
| 31 | +- **Output:** `[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]` |
| 32 | +- **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above. |
| 33 | + |
| 34 | +#### Example 2 |
| 35 | + |
| 36 | +- **Input:** `n = 1` |
| 37 | +- **Output:** `[["Q"]]` |
| 38 | +- **Explanation:** Here the number of rows and column is one thatswhy queen is placed in row 1 and column 1. |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +### Constraints |
| 43 | + |
| 44 | +- `1 <= n <= 9` |
| 45 | + |
| 46 | +### Approach |
| 47 | + |
| 48 | +To solve the problem, we can use the Backtracking technique technique. Here is the step-by-step approach: |
| 49 | + |
| 50 | +1. **Initialize :** |
| 51 | + -Start in the leftmost column |
| 52 | + -If all queens are placed return true |
| 53 | + -Try all rows in the current column. Do the following for every row. |
| 54 | +2. **Iterate Through the Array:** |
| 55 | + - Try all rows in the current column. Do the following for every row. |
| 56 | + -If the queen can be placed safely in this row |
| 57 | + -Then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution. |
| 58 | + -If placing the queen in [row, column] leads to a solution then return true. |
| 59 | + -If placing queen doesn’t lead to a solution then unmark this [row, column] then backtrack and try other rows. |
| 60 | + |
| 61 | +3. **Return Result:** |
| 62 | + -If all rows have been tried and valid solution is not found return false to trigger backtracking. |
| 63 | + |
| 64 | +### Solution Code |
| 65 | + |
| 66 | +#### Python |
| 67 | + |
| 68 | +``` |
| 69 | +# Python3 program to solve N Queen |
| 70 | +# Problem using backtracking |
| 71 | + |
| 72 | +global N |
| 73 | +N = 4 |
| 74 | + |
| 75 | + |
| 76 | +def printSolution(board): |
| 77 | + for i in range(N): |
| 78 | + for j in range(N): |
| 79 | + if board[i][j] == 1: |
| 80 | + print("Q",end=" ") |
| 81 | + else: |
| 82 | + print(".",end=" ") |
| 83 | + print() |
| 84 | + |
| 85 | + |
| 86 | +# A utility function to check if a queen can |
| 87 | +# be placed on board[row][col]. Note that this |
| 88 | +# function is called when "col" queens are |
| 89 | +# already placed in columns from 0 to col -1. |
| 90 | +# So we need to check only left side for |
| 91 | +# attacking queens |
| 92 | +def isSafe(board, row, col): |
| 93 | + |
| 94 | + # Check this row on left side |
| 95 | + for i in range(col): |
| 96 | + if board[row][i] == 1: |
| 97 | + return False |
| 98 | + |
| 99 | + # Check upper diagonal on left side |
| 100 | + for i, j in zip(range(row, -1, -1), |
| 101 | + range(col, -1, -1)): |
| 102 | + if board[i][j] == 1: |
| 103 | + return False |
| 104 | + |
| 105 | + # Check lower diagonal on left side |
| 106 | + for i, j in zip(range(row, N, 1), |
| 107 | + range(col, -1, -1)): |
| 108 | + if board[i][j] == 1: |
| 109 | + return False |
| 110 | + |
| 111 | + return True |
| 112 | + |
| 113 | + |
| 114 | +def solveNQUtil(board, col): |
| 115 | + |
| 116 | + # Base case: If all queens are placed |
| 117 | + # then return true |
| 118 | + if col >= N: |
| 119 | + return True |
| 120 | + |
| 121 | + # Consider this column and try placing |
| 122 | + # this queen in all rows one by one |
| 123 | + for i in range(N): |
| 124 | + |
| 125 | + if isSafe(board, i, col): |
| 126 | + |
| 127 | + # Place this queen in board[i][col] |
| 128 | + board[i][col] = 1 |
| 129 | + |
| 130 | + # Recur to place rest of the queens |
| 131 | + if solveNQUtil(board, col + 1) == True: |
| 132 | + return True |
| 133 | + |
| 134 | + # If placing queen in board[i][col |
| 135 | + # doesn't lead to a solution, then |
| 136 | + # queen from board[i][col] |
| 137 | + board[i][col] = 0 |
| 138 | + |
| 139 | + # If the queen can not be placed in any row in |
| 140 | + # this column col then return false |
| 141 | + return False |
| 142 | + |
| 143 | + |
| 144 | +# This function solves the N Queen problem using |
| 145 | +# Backtracking. It mainly uses solveNQUtil() to |
| 146 | +# solve the problem. It returns false if queens |
| 147 | +# cannot be placed, otherwise return true and |
| 148 | +# placement of queens in the form of 1s. |
| 149 | +# note that there may be more than one |
| 150 | +# solutions, this function prints one of the |
| 151 | +# feasible solutions. |
| 152 | +def solveNQ(): |
| 153 | + board = [[0, 0, 0, 0], |
| 154 | + [0, 0, 0, 0], |
| 155 | + [0, 0, 0, 0], |
| 156 | + [0, 0, 0, 0]] |
| 157 | + |
| 158 | + if solveNQUtil(board, 0) == False: |
| 159 | + print("Solution does not exist") |
| 160 | + return False |
| 161 | + |
| 162 | + printSolution(board) |
| 163 | + return True |
| 164 | + |
| 165 | +
|
| 166 | +``` |
| 167 | + |
| 168 | +#### Java |
| 169 | +``` |
| 170 | +
|
| 171 | +public class Solution { |
| 172 | + final int N = 4; |
| 173 | +
|
| 174 | + // A utility function to print solution |
| 175 | + void printSolution(int board[][]) |
| 176 | + { |
| 177 | + for (int i = 0; i < N; i++) { |
| 178 | + for (int j = 0; j < N; j++) { |
| 179 | + if (board[i][j] == 1) |
| 180 | + System.out.print("Q "); |
| 181 | + else |
| 182 | + System.out.print(". "); |
| 183 | + } |
| 184 | + System.out.println(); |
| 185 | + } |
| 186 | + } |
| 187 | +
|
| 188 | + // A utility function to check if a queen can |
| 189 | + // be placed on board[row][col]. Note that this |
| 190 | + // function is called when "col" queens are already |
| 191 | + // placeed in columns from 0 to col -1. So we need |
| 192 | + // to check only left side for attacking queens |
| 193 | + boolean isSafe(int board[][], int row, int col) |
| 194 | + { |
| 195 | + int i, j; |
| 196 | +
|
| 197 | + // Check this row on left side |
| 198 | + for (i = 0; i < col; i++) |
| 199 | + if (board[row][i] == 1) |
| 200 | + return false; |
| 201 | +
|
| 202 | + // Check upper diagonal on left side |
| 203 | + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) |
| 204 | + if (board[i][j] == 1) |
| 205 | + return false; |
| 206 | +
|
| 207 | + // Check lower diagonal on left side |
| 208 | + for (i = row, j = col; j >= 0 && i < N; i++, j--) |
| 209 | + if (board[i][j] == 1) |
| 210 | + return false; |
| 211 | +
|
| 212 | + return true; |
| 213 | + } |
| 214 | +
|
| 215 | + // A recursive utility function to solve N |
| 216 | + // Queen problem |
| 217 | + boolean solveNQUtil(int board[][], int col) |
| 218 | + { |
| 219 | + // Base case: If all queens are placed |
| 220 | + // then return true |
| 221 | + if (col >= N) |
| 222 | + return true; |
| 223 | +
|
| 224 | + // Consider this column and try placing |
| 225 | + // this queen in all rows one by one |
| 226 | + for (int i = 0; i < N; i++) { |
| 227 | + |
| 228 | + // Check if the queen can be placed on |
| 229 | + // board[i][col] |
| 230 | + if (isSafe(board, i, col)) { |
| 231 | + |
| 232 | + // Place this queen in board[i][col] |
| 233 | + board[i][col] = 1; |
| 234 | +
|
| 235 | + // Recur to place rest of the queens |
| 236 | + if (solveNQUtil(board, col + 1) == true) |
| 237 | + return true; |
| 238 | +
|
| 239 | + // If placing queen in board[i][col] |
| 240 | + // doesn't lead to a solution then |
| 241 | + // remove queen from board[i][col] |
| 242 | + board[i][col] = 0; // BACKTRACK |
| 243 | + } |
| 244 | + } |
| 245 | +
|
| 246 | + // If the queen can not be placed in any row in |
| 247 | + // this column col, then return false |
| 248 | + return false; |
| 249 | + } |
| 250 | +
|
| 251 | + // This function solves the N Queen problem using |
| 252 | + // Backtracking. It mainly uses solveNQUtil () to |
| 253 | + // solve the problem. It returns false if queens |
| 254 | + // cannot be placed, otherwise, return true and |
| 255 | + // prints placement of queens in the form of 1s. |
| 256 | + // Please note that there may be more than one |
| 257 | + // solutions, this function prints one of the |
| 258 | + // feasible solutions. |
| 259 | + boolean Solution() |
| 260 | + { |
| 261 | + int board[][] = { { 0, 0, 0, 0 }, |
| 262 | + { 0, 0, 0, 0 }, |
| 263 | + { 0, 0, 0, 0 }, |
| 264 | + { 0, 0, 0, 0 } }; |
| 265 | +
|
| 266 | + if (solveNQUtil(board, 0) == false) { |
| 267 | + System.out.print("Solution does not exist"); |
| 268 | + return false; |
| 269 | + } |
| 270 | +
|
| 271 | + printSolution(board); |
| 272 | + return true; |
| 273 | + } |
| 274 | +} |
| 275 | +
|
| 276 | +``` |
| 277 | + |
| 278 | +#### C++ |
| 279 | +``` |
| 280 | +
|
| 281 | +#include <bits/stdc++.h> |
| 282 | +#define N 4 |
| 283 | +using namespace std; |
| 284 | +
|
| 285 | +// A utility function to print solution |
| 286 | +void printSolution(int board[N][N]) |
| 287 | +{ |
| 288 | + for (int i = 0; i < N; i++) { |
| 289 | + for (int j = 0; j < N; j++) |
| 290 | + if(board[i][j]) |
| 291 | + cout << "Q "; |
| 292 | + else cout<<". "; |
| 293 | + printf("\n"); |
| 294 | + } |
| 295 | +} |
| 296 | +
|
| 297 | +// A utility function to check if a queen can |
| 298 | +// be placed on board[row][col]. Note that this |
| 299 | +// function is called when "col" queens are |
| 300 | +// already placed in columns from 0 to col -1. |
| 301 | +// So we need to check only left side for |
| 302 | +// attacking queens |
| 303 | +bool isSafe(int board[N][N], int row, int col) |
| 304 | +{ |
| 305 | + int i, j; |
| 306 | +
|
| 307 | + // Check this row on left side |
| 308 | + for (i = 0; i < col; i++) |
| 309 | + if (board[row][i]) |
| 310 | + return false; |
| 311 | +
|
| 312 | + // Check upper diagonal on left side |
| 313 | + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) |
| 314 | + if (board[i][j]) |
| 315 | + return false; |
| 316 | +
|
| 317 | + // Check lower diagonal on left side |
| 318 | + for (i = row, j = col; j >= 0 && i < N; i++, j--) |
| 319 | + if (board[i][j]) |
| 320 | + return false; |
| 321 | +
|
| 322 | + return true; |
| 323 | +} |
| 324 | +
|
| 325 | +// A recursive utility function to solve N |
| 326 | +// Queen problem |
| 327 | +bool solveNQUtil(int board[N][N], int col) |
| 328 | +{ |
| 329 | + // base case: If all queens are placed |
| 330 | + // then return true |
| 331 | + if (col >= N) |
| 332 | + return true; |
| 333 | +
|
| 334 | + // Consider this column and try placing |
| 335 | + // this queen in all rows one by one |
| 336 | + for (int i = 0; i < N; i++) { |
| 337 | + |
| 338 | + // Check if the queen can be placed on |
| 339 | + // board[i][col] |
| 340 | + if (isSafe(board, i, col)) { |
| 341 | + |
| 342 | + // Place this queen in board[i][col] |
| 343 | + board[i][col] = 1; |
| 344 | +
|
| 345 | + // recur to place rest of the queens |
| 346 | + if (solveNQUtil(board, col + 1)) |
| 347 | + return true; |
| 348 | +
|
| 349 | + // If placing queen in board[i][col] |
| 350 | + // doesn't lead to a solution, then |
| 351 | + // remove queen from board[i][col] |
| 352 | + board[i][col] = 0; // BACKTRACK |
| 353 | + } |
| 354 | + } |
| 355 | +
|
| 356 | + // If the queen cannot be placed in any row in |
| 357 | + // this column col then return false |
| 358 | + return false; |
| 359 | +} |
| 360 | +
|
| 361 | +// This function solves the N Queen problem using |
| 362 | +// Backtracking. It mainly uses solveNQUtil() to |
| 363 | +// solve the problem. It returns false if queens |
| 364 | +// cannot be placed, otherwise, return true and |
| 365 | +// prints placement of queens in the form of 1s. |
| 366 | +// Please note that there may be more than one |
| 367 | +// solutions, this function prints one of the |
| 368 | +// feasible solutions. |
| 369 | +bool Solution() |
| 370 | +{ |
| 371 | + int board[N][N] = { { 0, 0, 0, 0 }, |
| 372 | + { 0, 0, 0, 0 }, |
| 373 | + { 0, 0, 0, 0 }, |
| 374 | + { 0, 0, 0, 0 } }; |
| 375 | +
|
| 376 | + if (solveNQUtil(board, 0) == false) { |
| 377 | + cout << "Solution does not exist"; |
| 378 | + return false; |
| 379 | + } |
| 380 | +
|
| 381 | + printSolution(board); |
| 382 | + return true; |
| 383 | +} |
| 384 | +``` |
| 385 | + |
| 386 | +### Conclusion |
| 387 | + |
| 388 | +The N-Queens problem is a classic example of a combinatorial optimization problem that has been extensively studied in the field of computer science, particularly within the realms of algorithms and artificial intelligence. The problem is defined as placing N queens on an N×N chessboard in such a way that no two queens can attack each other. This means that no two queens can be placed in the same row, column, or diagonal. |
0 commit comments