Download as PPTX, PDF, TXT or read online from Scribd
Download as pptx, pdf, or txt
You are on page 1of 12
The N Queens Problem
Solving the Problem with
Backtracking Introduction to the N Queens Problem • • What is the N Queens Problem? • • The challenge is to place N queens on an N×N chessboard. • • No two queens should be able to attack each other. Rules and Constraints • • No two queens can be in the same row. • • No two queens can be in the same column. • • No two queens can be on the same diagonal. Example: 4-Queens Problem • • Visual Representation of a 4×4 chessboard with a sample solution. Backtracking Algorithm Overview • • Backtracking is a trial-and-error problem- solving approach. • • It builds a solution incrementally and abandons a path as soon as it's unviable. Steps of the Algorithm • 1. Start placing queens one by one in different rows. • 2. For each row, try all columns to check for safety. • 3. If placing a queen leads to a solution, return success. • 4. If not, backtrack and try the next possible placement. Pseudocode for N Queens • def solveNQueens(board, row): • if row >= N: • printSolution(board) • return • for col in range(N): • if isSafe(board, row, col): • board[row][col] = 1 • solveNQueens(board, row + 1) • board[row][col] = 0 # Backtrack isSafe Function • • Ensure no queens are in the same row, column, or diagonal. Time and Space Complexity • • Time Complexity: O(N!) • • Space Complexity: O(N²) • Explanation of why the time complexity is factorial. Applications • • AI and Robotics • • Constraint satisfaction problems • • Game theory and puzzle-solving Conclusion • • Backtracking helps in solving complex problems incrementally. • • N Queens is a great example to understand backtracking. Q&A • Open for questions.