【ACWing】1116. Horse walking day

Subject address:

https://www.acwing.com/problem/content/1118/

Horses move in Chinese chess in a Japanese pattern. Please write a program, given n ∗ mn*mnm- size chess board, and the initial position of the horse(x, y) (x, y)(x,y ) , it is required that the same point on the chessboard cannot be repeatedly passed, and how many ways the horse can traverse all the points on the chessboard.

Input format: the
first line is an integer TTT represents the number of test data groups. Each set of test data contains one line, four integers, which are the size of the chessboard and the initial position coordinatesn, m, x, yn, m, x, yn,m,x,and

Output format:
Each set of test data contains one line, which is an integer, which represents the total number of ways the horse can traverse the chessboard. If it cannot traverse all the points on the chessboard, it will output 0 00

Data range:
1 ≤ T ≤ 9 1≤T≤91T9
1 ≤ m , n ≤ 9 1≤m,n≤9 1m,n9
0 ≤ x ≤ n − 1 0≤x≤n−1 0xn1
0 ≤ y ≤ m − 1 0≤y≤m−1 0Ym1

Starting from a certain state, each step will go to a fork in the search tree. Since the path is not only related to which grids are passed, but also how to go (that is, which direction each step is to go), so search The nodes in the tree do not overlap, and can only use DFS brute force search. The legal state is that the number of grids passed is exactly nm nmn m time. You can't go out of bounds at every step, and you can't go to the grid you've walked before. code show as below:

#include <iostream>
#include <cstring>
using namespace std;

const int N = 10;
int dx[] = {
    
    -1, -2, -2, -1, 1, 2, 2, 1};
int dy[] = {
    
    -2, -1, 1, 2, 2, 1, -1, -2};
int m, n;
// 记录哪些格子被走过
bool st[N][N];
// 用个全局变量记录走过的格子数量
int res;

// cnt记录走过了多少个格子
void dfs(int x, int y, int cnt) {
    
    
    st[x][y] = true;
    cnt++;

    if (cnt == n * m) res++;
    else 
        for (int i = 0; i < 8; i++) {
    
    
            int nx = x + dx[i], ny = y + dy[i];
            if (0 <= nx && nx < n && 0 <= ny && ny < m && !st[nx][ny])
                dfs(nx, ny, cnt);
        }

    st[x][y] = false;
}

int main() {
    
    
    int T;
    cin >> T;
    while (T--) {
    
    
        int x, y;
        cin >> n >> m >> x >> y;
        memset(st, false, sizeof st);

        res = 0;
        dfs(x, y, 0);

        cout << res << endl;
    }

    return 0;
}

Time complexity is exponential, space O (nm) O(nm)O(nm)

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/114814176