ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

回溯解马踏棋盘之跑死的马

2021-11-13 14:34:42  阅读:145  来源: 互联网

标签:qp return 解马 int max else 回溯 棋盘 true


回溯本身没问题,但是运行时间过长,当棋盘大小为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 }

 

标签:qp,return,解马,int,max,else,回溯,棋盘,true
来源: https://www.cnblogs.com/qian-136/p/15548239.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有