本文共 1633 字,大约阅读时间需要 5 分钟。
今天从早上开始就在弄回溯法,都说回溯的经典问题是八皇后问题,于是就好好看了一下八皇后的问题。找出所有的情况可能有点难,但是找出一条路来感觉应该挺简单的。
我一直都不怎么会用递归,这个程序依然没有递归。
-
-
-
- public class Huisu02 {
-
- public static boolean isdianogal(int x,int y,int[] points){
-
- int xx=0,yy=0;
- xx=x>y?x-y: 0;
- yy=x>y? 0 :y-x;
- for (int i = yy; i < y; i++) {
- if(points[i]==xx){
- return true;
- }
- xx++;yy++;
- }
-
- xx=x+y<=7?x+y:7;
- yy=x+y<=7?0:x+y-7;
- for (int i = yy; i < y; i++) {
- if(points[i]==xx){
- return true;
- }
- xx--;yy++;
- }
- return false;
- }
- public static void huisu(){
-
- }
- public static void main(String[] args) {
-
- int[] samerow = new int[8];
- int[] points=new int[8];
- int index=0;
- boolean backed=false;
- points[index++]=0;
- samerow[0]=1;
- while (index<8) {
- int i=0;
- if(!backed){
- for (i = 0; i < points.length; i++) {
- if(samerow[i]==0){
- if(!isdianogal(i, index, points)){
- points[index++]=i;
- samerow[i]=1;
- break;
- }
- }
- }
- }else {
- for (i = points[index]+1; i < points.length; i++) {
- if(samerow[i]==0){
- if(!isdianogal(i, index, points)){
- points[index++]=i;
- backed=false;
- samerow[i]=1;
- break;
- }
- }
- }
- }
-
- if(i>=8){
-
- index--;
- samerow[points[index]]=0;
- backed=true;
- }
- }
-
- int[][] cheesbord = new int[8][8];
- int j=0;
- for (int i = 0; i < points.length; i++) {
- cheesbord[i][points[j]]=1;
- j++;
- }
-
- for (int i = 0; i < 8; i++) {
- for (j = 0; j < 8; j++) {
- if(cheesbord[i][j]==1){
- System.err.print(cheesbord[i][j]+" ");
- }
- System.err.print("# ");
- }
- System.err.println();
- }
- }
- }
对于八皇后问题的描述在ppt里面。
转载地址:http://ouxql.baihongyu.com/