Backtracking Leetcode Summary, Part 1
- N-Queens
- Permutation
N-Queens:
Problem Description: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
Thought Process in Short: Backtracking with DFS. We know each row has one queen, so we move from top line to the bottom line line by line, checking each column, and two diagonals.
Few Key Points:
- For all “hill” diagonals row + column = const, and for all “dale” diagonals row - column = const.
- There could be the only one queen in a row and the only one queen in a column.
Algorithms:
- Start from the first row = 0.
- Iterate over the columns and try to put a queen in each column.
- If square (row, column) is not under attack
- Place the queen in (row, column) square.
- Exclude one row, one column and two diagonals from further consideration.
- If all rows are filled up row == N
- That means that we find out one more solution.
Else - Proceed to place further queens backtrack(row + 1).
- That means that we find out one more solution.
- Now backtrack : remove the queen from (row, column) square.
- If square (row, column) is not under attack
Codes:
Initialize log variables:
1 | int rows[]; |
Checking if a cell is under attack:
1 | public boolean isNotUnderAttack(int row, int col) { |
Method placing and removing queens:
1 | public void placeQueen(int row, int col) { |
Adding a solution to existing solutions:
1 | public void addSolution() { |
The actual backtracking process:
1 | public void backtrack (int row) { |
Main function of solution:
1 | public List<List<String>> solveNQueens(int n) { |
Permutation:
One of the more basic backtracking problem.
Algorithms:
- If the first integer to consider has index n that means that the current permutation is done.
- Iterate over the integers from index first to index n - 1.
- Place i-th integer first in the permutation, i.e. swap(nums[first], nums[i]).
- Proceed to create all permutations which starts from i-th integer : backtrack(first + 1).
- Now backtrack, i.e. swap(nums[first], nums[i]) back.
Code:
BFS to find solutions, then backtracking to reverse to previous states. The following is the backtracking part.
1 | public void backtrack(int n, |
Main function of solution:
1 | public List<List<Integer>> permute(int[] nums) { |