zoukankan      html  css  js  c++  java
  • 【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;
    }
    


     

  • 相关阅读:
    Java中String的intern方法
    3.7测试复盘
    3.6测试复盘
    LTMU论文解析
    移动机器人相机模型:从相机移动到二维图像
    一步步分析MIPS数据通路(单周期)
    Slam笔记I
    如何理解SiamRPN++?
    如何使用Pytorch迅速写一个Mnist数据分类器
    PySide2的This application failed to start because no Qt platform plugin could be initialized解决方式
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7632485.html
Copyright © 2011-2022 走看看