1. 程式人生 > 其它 >回溯解馬踏棋盤之跑死的馬

回溯解馬踏棋盤之跑死的馬

回溯本身沒問題,但是執行時間過長,當棋盤大小為7*7時約10秒,棋盤大小為8*8時時間未知(還沒跑完)

程式碼寫註釋了,就不另外作介紹了

 1 import java.util.Scanner;
 2 
 3 public class m {
 4     static int max = 8;
 5     static int[][] qp = new int[max][max];
 6     static int con = 0;
 7 
 8     public static void main(String[] args) {
 9         //初始化棋盤
10         for
(int i = 0; i < max; i++) { 11 for (int j = 0; j < max; j++) { 12 qp[i][j] = 0; 13 } 14 } 15 16 sx(qp, 3, 3); 17 //執行結束後列印 18 print(); 19 } 20 21 private static boolean sx(int[][] qp, int i, int j) { 22 //如果格子已都被跳過一次 結束執行
23 if (con == max*max) { 24 return true; 25 } else if (hf(qp, i, j)) { //假設當前位置可行 26 con++; 27 qp[i][j] = con; 28 //遞迴嘗試8個位置 29 if (sx(qp, i + 1, j - 2)) { 30 return true; 31 } else if (sx(qp, i + 2, j + 1)) {
32 return true; 33 } else if (sx(qp, i + 2, j - 1)) { 34 return true; 35 } else if (sx(qp, i - 2, j - 1)) { 36 return true; 37 } else if (sx(qp, i - 2, j + 1)) { 38 return true; 39 } else if (sx(qp, i - 1, j + 2)) { 40 return true; 41 } else if (sx(qp, i + 1, j + 2)) { 42 return true; 43 } else if (sx(qp, i - 1, j - 2)) { 44 return true; 45 }else { 46 //確認當前位置不行 回溯到上一位置 47 con--; 48 qp[i][j] = 0; 49 return false; 50 } 51 } else { 52 return false; 53 } 54 } 55 56 private static boolean hf(int[][] qp, int i, int j) { 57 //判斷當前位置在棋盤內 58 if (i >= max || i < 0 || j >= max || j < 0) { 59 return false; 60 //判斷當前位置沒走過(為0) 61 } else if (qp[i][j] != 0) { 62 return false; 63 } 64 return true; 65 } 66 //輸出 67 public static void print(){ 68 Scanner sc=new Scanner(System.in); 69 for (int i = 0; i < max; i++) { 70 for (int j = 0; j < max; j++) { 71 System.out.print(qp[i][j] + "\t"); 72 } 73 System.out.println(); 74 } 75 sc.next(); 76 } 77 }