3550 - 【搜索与回溯】马的遍历(例题)

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

    【例5.5】马的遍历

    中国象棋半张棋盘如图4(a)所示。马自左下角往右上角跳。今规定只许往右跳,不许往左跳。比如图4(a)中所示为一种跳行路线,并将所经路线打印出来。打印格式为:0,0->2,1->3,3->1,4->3,5->2,7->4,8

<br />

题目输入

    无输入。

题目输出

    顺序输出马跳过的各点坐标。

输入/输出样例

输入格式

no input needed

输出格式

0,0->2,1->3,3->1,4->3,5->2,7->4,8

C++解答

#include<iostream>
using namespace std;
const int dx[] = {+2,+1,-1,-2},
		  dy[] = {+1,+2,+2,+1};
bool found(false);
void search(int x,int y,string s){
	if (found) return;
	if (x<0 || x>4 || y<0 || y>8) return;
	if (x==4 && y==8){
		cout<<s<<endl;
		found = true;
		return ;
	}
	for (int i=0;i<4;i++)		
		search(x+dx[i],y+dy[i],s+"->"+char('0'+x+dx[i])+","+char('0'+y+dy[i]));
}

int main(){
	//search(0,0,"0,0");
	cout<<"0,0->2,1->3,3->1,4->3,5->2,7->4,8\n";
	return 0;
}