zoukankan      html  css  js  c++  java
  • 马的走法(DFS)

    题目

    Description
    在一个4×5的棋盘上,输入马的起始位置坐标(纵,横)位置,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。

    Input
    输入只有一行,包括两个整数,既马的起始位置坐标x和y值,并且,这个坐标一定在4×5的小棋盘上,即 0<x<=4, 0<y<="5. 
    Output
    一个整数,为能返回到初始位置的所有不同走法的总数。

    Sample Input
    Original Transformed
    2   2
    1   1
    1   3
    

    Sample Output
    Original Transformed
    4596
    1508
    4772
    

    分析:DFS

    代码

    #include<iostream>
    #include<cstdio>
    #include<queue>
    #include<string>
    #include<cstring>
    using namespace std;
    int next1[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
    int book[10][10],sum;
    int a,b;
    int dfs(int x,int y)
    {
       int tx,ty;
       for(int k=0;k<8;k++)
        {
            tx=x+next1[k][0];
            ty=y+next1[k][1];
            if(tx==a&&ty==b)
                sum++;
            if(tx<1||tx>4||ty<1||ty>5)
                continue;
            if(book[tx][ty]==0)
            {
                book[tx][ty]=1;
                dfs(tx,ty);
                book[tx][ty]=0;
            }
        }
    return sum;
    }
    int main()
    {
        while(~scanf("%d%d",&a,&b))
        {
            sum=0;
            memset(book,0,sizeof(book));
            book[a][b]=1;
            printf("%d
    ",dfs(a,b));
        }
        return 0;
    }
    

  • 相关阅读:
    D
    洛谷P2002 消息扩散
    洛谷P5058 [ZJOI2004]嗅探器
    洛谷P2746 校园网Network of Schools
    洛谷P3388 【模板】割点(割顶)
    洛谷P1407 [国家集训队]稳定婚姻
    2018年12月18日
    洛谷P1547 Out of Hay
    洛谷P4018 Roy&October之取石子
    洛谷P1318 积水面积
  • 原文地址:https://www.cnblogs.com/nickqiao/p/7583378.html
Copyright © 2011-2022 走看看