这段代码中的问题在于递归调用的dfs函数没有终止条件,导致堆栈溢出。在dfs函数中,应该加上终止条件,当x和y的值等于targetX和targetY时,返回。修改后的代码如下:

void dfs(int n, int m, int x, int y, int targetX, int targetY, int& count) {
    if (x == targetX && y == targetY) {
        count++;
        return;
    }
    
    static int dx[] = {1, 1, 0, -1, -1, -1, 0, 1};
    static int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};
    
    for (int i = 0; i < 8; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        
        if (validPosition(n, m, nx, ny)) {
            dfs(n, m, nx, ny, targetX, targetY, count);
        }
    }
}

int num(int n, int m, int x1, int y1, int x2, int y2) {
    int count = 0;
    dfs(n, m, x1, y1, x2, y2, count);
    return count;
}

int main() {
    cout << num(4, 4, 1, 1, 3, 3);
    return 0;
}

运行结果为:2。表示从(1,1)到(3,3)的路径有2条

#include iostream#include vectorusing namespace std;bool validPositionint n int m int x int y return x = 0 && x n && y = 0 && y m;void dfsint n int m int x int y int targetX int targetY int& cou

原文地址: https://www.cveoy.top/t/topic/hFB8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录