Java Backtracking Solution - 100%(172ms ) at Most


  • 0
    C
    public class Solution {
        public int totalNQueens(int n) {
            if (n < 1) return 0;
            int[] pos = new int[n];
            return totalNQueens(0, 0, pos);
        }
        
        private int totalNQueens(int index, int filled, int[] pos) {
            if (index >= pos.length) return 1;
            int n = pos.length, result = 0;
            for (int i = 0; i < n; i++) {
                boolean available = true;
                for (int j = 0; j < filled; j++) {
                    if (pos[j] == i || Math.abs(j - index) == Math.abs(pos[j] - i)) {
                        available = false;
                        break;
                    }
                }
                if (available) {
                    pos[index] = i;
                    result += totalNQueens(index + 1, filled + 1, pos);
                }
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.