【5003】马遍历问题

Time Limit: 10 second
Memory Limit: 2 MB

问题描述

中国象棋棋盘如图所示。马自左下角(0,0)往右上角(8,9)跳。今规定只许往右跳,不许往左跳。
求出所有可行的跳行路线。比如图中所示为第一种跳行路线,并将所经路线按如下格式输出:
1:(0,0)->(1,2)->(2,4)->(3,6)->(4,8)->(6,9)->(7,7)->(8,9)

Input

无输入文件

Output

输出所有可行的行走路线
格式为:1{序号}:(0,0)->(1,2)->(2,4)->(3,6)->(4,8)->(6,9)->(7,7)->(8,9){方案}
输出方案中,输出优先顺序为(i+1,j+2)>(i+2,j+1)>(i+2,j-1)>(i+1,j-2)。其中(i,j)代表马当前位置,i是横坐标,j是纵坐标。

Sample Input


Sample Output

1:(0,0)->(1,2)->(2,4)->(3,6)->(4,8)->(6,9)->(7,7)->(8,9)
2:(0,0)->(1,2)->(2,4)->(3,6)->(4,8)->(5,6)->(6,8)->(8,9)
3:......
4:......
5:......
......

【题解】

从0,0开始按照题目的顺序搜索就可以了,深搜。最后打印方案。

【代码】

#include <cstdio>

const int MAXP = 10;

bool can[MAXP][MAXP];
int step = 0,ans[1000][3],nans = 0;

void init() //初始化数组,一开始所有的位置都可以走。can
{
    for (int i = 0;i <= 8;i++)
        for (int j = 0;j <= 9;j++)
            can[i][j] = true;
}

void tr_y(int x,int y) //尝试到(x,y)这个位置
{
    if (x > 8) return;
    if (y > 9) return;
    if (y < 0) return;
    if (!can[x][y]) return; //这之前都用于判断x,y这个位置能否到达.
    can[x][y] = false; //置这个位置不能再走。
    step++;//步骤数增加
    ans[step][1] = x;//记录下答案。
    ans[step][2] = y;
    tr_y(x+1,y+2); //按照题目给的顺序去搜索。
    tr_y(x+2,y+1);
    tr_y(x+2,y-1);
    tr_y(x+1,y-2);
    if (x == 8 && y == 9) //如果到了终点 就输出方案。
        {
            nans++;
            printf("%d:",nans);
            for (int i = 1;i <= step-1;i++)
                printf("(%d,%d)->",ans[i][1],ans[i][2]);
            printf("(%d,%d)
",ans[step][1],ans[step][2]);
        }
    can[x][y] = true; //回溯到之前的状态
    step--;
}

int main()
{
    init();
    tr_y(0,0);
    return 0;
}


 

原文地址:https://www.cnblogs.com/AWCXV/p/7632485.html