1. 程式人生 > >Leetcode 51.N後問題

Leetcode 51.N後問題

N後問題

皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,並且使皇后彼此之間不能相互攻擊。

上圖為 8 皇后問題的一種解法。

給定一個整數 n,返回所有不同的 皇后問題的解決方案。

每一種解法包含一個明確的 n 皇后問題的棋子放置方案,該方案中 'Q' 和 '.' 分別代表了皇后和空位。

示例:

輸入: 4

輸出: [

[".Q..", // 解法 1

"...Q",

"Q...",

"..Q."],

 

["..Q.", // 解法 2

"Q...",

"...Q",

".Q.."]

]

解釋: 4 皇后問題存在兩個不同的解法。

 

 1 import java.util.*;
 2 
 3 public class Solution{
 4     public List<List<String>> solveNQueens(int n){
 5         List<List<String>> res=new ArrayList<List<String>>();
 6         int[] queenList=new int[n];//第i個位置存放的數表示row行時,Q的列
7 placeQueen(queenList,0,n,res);//在第0行放Q 8 return res; 9 } 10 11 private void placeQueen(int[] queenList,int row,int n,List<List<String>> res){ 12 if(row==n){ 13 ArrayList<String> list=new ArrayList<String>(); 14 for(int
i=0;i<n;i++){ 15 String str=""; 16 for(int col=0;col<n;col++){ 17 if(queenList[i]==col){ 18 str+="Q"; 19 }else{ 20 str+="."; 21 } 22 } 23 list.add(str); 24 } 25 res.add(list); 26 } 27 for(int col=0;col<n;col++){ 28 if(isValid(queenList,row,col)){ 29 queenList[row]=col; 30 placeQueen(queenList,row+1,n,res); 31 } 32 } 33 } 34 35 private boolean isValid(int[] queenList,int row,int col){ 36 for(int i=0;i<row;i++){ 37 int pos=queenList[i]; 38 if(pos==col) 39 return false; 40 if(pos+row-i==col) 41 return false; 42 if(pos-row+i==col) 43 return false; 44 } 45 return true; 46 } 47 }