AcWing 1116. 馬走日(遍歷棋盤的路徑總數)

題目鏈接:點擊這裏

在這裏插入圖片描述

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 15;

int dx[] = {-1, -2, -2, -1, 1, 2, 2, 1};
int dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};

bool st[N][N];
int n, m, sx, sy;
int ans = 0;

void dfs(int x, int y, int now)
{
    if(now == n * m)
    {
        ans++;
        return ;
    }
    
    st[x][y] = true;
    
    for(int i = 0; i < 8; ++i)
    {
        int a = x + dx[i], b = y + dy[i];
        
        if(a < 0 || a >= n || b < 0 || b >= m)    continue;
        if(st[a][b])    continue;
        
        dfs(a, b, now + 1);
    }
    
    st[x][y] = false;       // 恢復現場
}

int main()
{
    int T;
    cin >> T;
    while(T--)
    {
        memset(st, false, sizeof st);
        
        cin >> n >> m >>sx >> sy;
        
        ans = 0;
        dfs(sx, sy, 1);
        
        cout << ans << endl;
    }
    
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章