LeetCode52-N皇后 II
LeetCode52-N皇后 II 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public int totalNQueens (int n) { if (n < 1 ) return 1 ; queens = new int [n]; cols = new boolean [n]; left = new boolean [(n << 1 ) - 1 ]; right = new boolean [left.length]; place(0 ); return way; } int [] queens; boolean [] cols; boolean [] left; boolean [] right; int way; void place (int row) { if (row == queens.length) { way++; return ; } for (int col = 0 ; col < cols.length; col++) { if (cols[col]) continue ; int leftIndex = row - col + cols.length - 1 ; if (left[leftIndex]) continue ; int rightIndex = row + col; if (right[rightIndex]) continue ; queens[row] = col; cols[col] = true ; left[leftIndex] = true ; right[rightIndex] = true ; place(row + 1 ); cols[col] = false ; left[leftIndex] = false ; right[rightIndex] = false ; } }