[LeetCode]N-Queens II

來源:互聯網
上載者:User

標籤:blog   http   java   2014   io   for   

題目:給定一個整數n,表示棋盤的規模是n*n,在棋盤上放置n個皇后,要求同一行,同一列,同一條對角線不能有相同的皇后,求出可行的方案數

演算法:深度優先搜尋 + 剪枝最佳化

剪枝最佳化方案如下(拿4皇后為例):

不難發現存在下列規律:

同一條左對角線:row - col + n = 恒定值
同一條右對角線:row + col = 恒定值

public class Solution {    final int CHECK_NUMBER = 3;  // check tree points: col, left diagonal and right diagonal    final int MAX_NUMBER = 1024;        int nSolutions = 0;boolean[][] isVisited = new boolean[CHECK_NUMBER][MAX_NUMBER];public int totalNQueens(int n) {        for (int i=0; i<CHECK_NUMBER; ++i) {        isVisited[i] = new boolean[MAX_NUMBER];        }                dfs(0, n);        return nSolutions;    }/** * boolean[0][MAXN]: * * 0: check the col * 1: check the left diagonal * 2. check the right diagonal *  */public void dfs(int row, int nGirds) {if (row == nGirds) {++nSolutions;return ;}for (int col=0; col<nGirds; ++col) {if (!isVisited[0][col]  && !isVisited[1][row-col+nGirds] && !isVisited[2][row+col]) {isVisited[0][col] = true;isVisited[1][row-col+nGirds] = true;isVisited[2][row+col] = true;dfs(row+1, nGirds);isVisited[0][col] = false;isVisited[1][row-col+nGirds] = false;isVisited[2][row+col] = false;}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.