1.問題描述:
在國際象棋中,馬走日,用戶輸入棋盤的起始位置從x:0-4,y:0-3輸出從這一點開始,馬走完整個棋盤的各個方案,並輸出方案數
2.輸入樣式:
請輸入棋盤馬起始位置:
0 0
3.輸出樣式:
1 4 17 12
18 13 2 5
3 8 11 16
14 19 6 9
7 10 15 20
==========================
1 4 15 20
14 19 2 5
3 8 11 16
18 13 6 9
7 10 17 12
==========================
.......
4.解題思路:
我們用一個二維數組模擬馬走的方向,通過函數move(x,y),來達到馬走。 如果棋盤next_x>=0 && next_x<=4 && next_y>=0 && next_y<=3表示next_x,next_y在棋盤內,棋盤qipan[next_x][next_y] = = 0表示起盤沒有走過,即下一步滿足這些條件,則把下一步置為走過的狀態,step++,調用move(next_x,next_y)函數,調用完再回溯。
5.代碼實例:
package com.zzl;
import java.util.Scanner;
/**
* 1.問題描述 在國際象棋中,馬只能走日,但是馬位於不同的方位可以走的方向有所區別
* 當馬位於棋盤中間位置的時候
*
*
*/
public class 馬踏棋盤問題求解 {
//馬能走的8個方向
static int weizhi[][] = {{-2,1},{-2,-1},{-1,2},{-1,-2},{1,2},{1,-2},{2,1},{2,-1}};
static int step = 1;//先走哪一步,步數
static int qipan[][] = new int[5][4];
static int count = 0;
public static void main(String[] args) {
//初始化棋盤
for(int i=0;i<qipan.length;i++){
for(int j=0;j<qipan[i].length;j++){
qipan[i][j] = 0;
}
}
//輸入起始位置,起始位置從1,1開始算 ,計算機數組從0,0開始算,所以x--,y--;
Scanner scn = new Scanner(System.in);
System.out.println("請輸入棋盤馬起始位置:");
int x = scn.nextInt();
int y = scn.nextInt();
qipan[x][y] = step;
step++;
move(x,y);
System.out.println("共有" + count + "種方案");
}
public static void move(int x, int y) {
int next_x = 0;
int next_y = 0;
if(step>20){
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
System.out.printf("%5d",qipan[i][j]);
}
System.out.println();
}
System.out.println("==========================");
count ++;
return;
}else{
for(int i=0;i<8;i++){
next_x = x + weizhi[i][0];
next_y = y + weizhi[i][1];
//下一步棋滿足條件
if(next_x>=0 && next_x<=4 && next_y>=0 && next_y<=3 && qipan[next_x][next_y] ==0){
qipan[next_x][next_y] = step;
step++;
move(next_x,next_y);
step--;
qipan[next_x][next_y] = 0;
}
}
}
}
}