zoukankan      html  css  js  c++  java
  • 52. N-Queens II

    class Solution {
        public int totalNQueens(int n) {
            int[][] board=new int[n][n];
            return totalNQueens(0, board);
        }
        private int totalNQueens(int i, int[][] board)
        {
            if(i==board.length)
                return 1;
            int ret=0;
            for(int j=0;j<board.length;j++)
                if(board[i][j]==0)
                {
                    board[i][j]=1;
                    fillQueuePath(i, j, board, -1);
                    ret+=totalNQueens(i+1,board);
                    fillQueuePath(i, j, board, 1);
                    board[i][j]=0;
                }
            return ret;
        }
        private void fillQueuePath(int i, int j, int[][] board, int val){
            for(int k=1;i+k<board.length;k++)
            {
                board[i+k][j]+=val;
                if(j-k>=0)
                    board[i+k][j-k]+=val;
                if(j+k<board.length)
                    board[i+k][j+k]+=val;
            }
        }    
    }
    class Solution {
        public int totalNQueens(int n) {
            boolean[] cols=new boolean[n];
            boolean[] d1=new boolean[n*2];
            boolean[] d2=new boolean[n*2];
            return totalNQueens(0, cols, d1, d2);
        }
        private int totalNQueens(int i, boolean[] cols, boolean[] d1, boolean[] d2)
        {
            if(i==cols.length)
                return 1;
            int ret=0;
            for(int j=0;j<cols.length;j++)
            {
                int dn1=i-j+cols.length;
                int dn2=i+j;
                if(cols[j]==false&&d1[dn1]==false&&d2[dn2]==false)
                {
                    cols[j]=true;
                    d1[dn1]=true;
                    d2[dn2]=true;
                    ret+=totalNQueens(i+1,cols, d1, d2);
                    cols[j]=false;
                    d1[dn1]=false;
                    d2[dn2]=false;
                }
            }
            return ret;
        }
    }
  • 相关阅读:
    爬虫入门
    读写文件操作
    列表的操作
    课后习题小练
    Python切片
    逗号的麻烦
    字符串学与练
    Turtle的学习
    FTL(FreeMarker)基础
    java反射机制基础
  • 原文地址:https://www.cnblogs.com/asuran/p/7594688.html
Copyright © 2011-2022 走看看