Solve N-Queens Problem in PHP with Backtracking
This Snippet is coded by a user inOnline php Compiler. You can see and run this code too.
زبان: PHP
This PHP code solves the classic N-Queens problem using the Backtracking algorithm. The goal is to place N queens on an N×N chessboard so that no two queens attack each other. The function solveNQueens(8) sets the number of queens to 8 and prints all possible solutions.
The algorithm works column by column, trying each row in the current column. The isSafe function checks if placing a queen at a given cell conflicts with previously placed queens. It checks the row, main diagonal, and secondary diagonal. If the cell is safe, the queen is placed and the algorithm proceeds to the next column; otherwise, it backtracks and tries another row.
The output is a visual representation of the board for each solution, where each cell is marked with . or Q. You can change the number of queens by modifying the argument in solveNQueens().