马走日 OpenJ_Bailian - 4123(Dfs)

整个题可以简单理解为求有几种遍历一个图的路径,一个简单的找路径DFS就可以了,其中有两个小技巧、

传参时多传一个dep(当前步数),可以很方便的判断是否已经走完(n*m)

注意边界问题!

//马走日
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 15;
bool chess[maxn][maxn]; //false表示没有走过
int sx[8]={1,1,-1,-1,2,2,-2,-2};
int sy[8]={2,-2,2,-2,1,-1,1,-1};
int T, n, m, x, y, ans = 0;

void Dfs(int dep, int x, int y)
{
    //是否已经全部走完
    if(n*m == dep){
        ans++;
        return;
    }
    //对于每个可以走的点
    for(int r = 0; r < 8; r++){
        int s = x + sx[r]; int t = y + sy[r];
        if (!chess[s][t] && s>0 && t>0 && s<=n && t<=m){
			chess[s][t]=true;
			Dfs(dep+1, s, t);//标记为旧点
			chess[s][t]=false;//回溯
		}
    }
}

int main()
{
    scanf("%d",&T);
    while(T--){
        scanf("%d%d%d%d",&n,&m,&x,&y);
        ++x, ++y;
        memset(chess, 0, sizeof(chess));
        ans = 0; chess[x][y] = true;
        Dfs(1, x, y);
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/82289244