美文网首页计算机
Leetcode - N-Queens II

Leetcode - N-Queens II

作者: Richardo92 | 来源:发表于2016-09-23 14:13 被阅读5次

    My code:

    public class Solution {
        private int counter = 0;
        public int totalNQueens(int n) {
            if (n <= 0) {
                return 0;
            }
            
            helper(0, new boolean[n], new boolean[2 * n], new boolean[2 * n], n);
            return counter;
        }
        
        private void helper(int row, boolean[] col, boolean[] l1, boolean[] l2, int n) {
            if (row >= n) {
                counter++;
                return;
            }
            for (int i = 0; i < n; i++) {
                int index1 = row - i + n;
                int index2 = 2 * n - i - row - 1;
                if (!col[i] && !l1[index1] && !l2[index2]) {
                    col[i] = true;
                    l1[index1] = true;
                    l2[index2] = true;
                    helper(row + 1, col, l1, l2, n);
                    col[i] = false;
                    l1[index1] = false;
                    l2[index2] = false;
                }
            }
        }
    }
    

    就把 I 改了下,就交了。思路差不多。
    核心就是,那两条对称斜线,是可以各用一个数字来表示的。

    Anyway, Good luck, Richardo! -- 09/23/2016

    相关文章

      网友评论

        本文标题:Leetcode - N-Queens II

        本文链接:https://www.haomeiwen.com/subject/bgptyttx.html