1. 程式人生 > 實用技巧 >N皇后問題

N皇后問題

題目

N皇后問題是指在N*N的棋盤上要擺N個皇后,要求任何兩個皇后不同行,不同列也不再同一條斜線上,求給一個整數n,返回n皇后的擺法。

解析1

  ——我的解法——case:87.5%——執行超時

  使用HashMap記錄合法的皇后位置,使用遞迴探索所有可能性,最後通過回溯得到所有的解法。

  注意點:在遞迴進入下一階段時,需要使用全新的HashMap。主要是避免當前階段的HashMap被汙染後不能重用。

code1

 1 /**
 2      *
 3      * @param n int
 4      * 
@return int 5 * case通過率:87.5 6 * 錯誤原因:執行時間過大 7 */ 8 public static int Nqueen (int n) { 9 int total=0; 10 Map<Integer,Integer> map = new HashMap<>(); 11 //設定在第一行放置皇后的位置 12 for(int i=0;i<n;i++){ 13 map.put(0,i); 14 total+=deal(map,1,n);
15 } 16 //返回最終結果 17 return total; 18 } 19 //開始遞迴解決 20 public static int deal(Map<Integer,Integer> map,int x,int n){ 21 //已經放置了n個皇后,表示策略成功 22 if(x==n && map.size()==n){ 23 return 1; 24 }else if(x==n && map.size()!=n){
25 return 0; 26 }else{ 27 int total=0; 28 Map<Integer,Integer> nextMap = new HashMap<>(); 29 for(int i=0;i<n;i++){ 30 //判斷橫、縱,斜線是否已經放置了皇后:因為是從上往下,所以斜線判斷縮小為 31 //只判斷左上和右上 32 if(!map.containsKey(x) && !map.containsValue(i) && !hasOther(map,x,i,n)){ 33 nextMap.putAll(map); 34 nextMap.put(x,i); 35 total+=deal(nextMap,x+1,n); 36 } 37 } 38 // System.out.println("\n當前total:"+total); 39 return total; 40 } 41 } 42 43 /** 44 * 45 * 判斷左上斜線和右上斜線是否已經被放置 46 * @param map 47 * @param x 48 * @param y 49 * @param n 50 * @return 51 */ 52 public static boolean hasOther(Map<Integer,Integer> map,int x,int y,int n){ 53 int i=x-1; 54 int j=y-1; 55 while(i>=0 && j>=0){ 56 if(map.containsKey(i) && map.get(i)==j){ 57 /*System.out.print(i+","+j+" ");*/ 58 return true; 59 } 60 i--; 61 j--; 62 } 63 i = x-1; 64 j = y+1; 65 while(i>=0 && j<n){ 66 if(map.containsKey(i) && map.get(i)==j){ 67 /*System.out.print(i+","+j+" ");*/ 68 return true; 69 } 70 i--; 71 j++; 72 } 73 return false; 74 }
View Code

===================================================================================================================================

解析2:

  ——參考的別人的程式碼

  ——原文連結:https://www.nowcoder.com/questionTerminal/c76408782512486d91eea181107293b6?toCommentId=7209950