@Yezi.press
二维矩阵 DFS 搜索模板
DFS 搜索二维矩阵中从 (1, 1) 到 (n, m) 的路线数量
算法模板发布于 2026/08/22#dfs
C++31 行703 Bytes
#include <bits/stdc++.h>
using namespace std;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
const int N = 105; // 根据题目数据范围调整
bool vis[N][N];
int n, m, cnt = 0;
void dfs(int x, int y) {
if (x == n && y == m) { cnt++; return; } // 到达终点
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny])
continue;
vis[nx][ny] = 1;
dfs(nx, ny);
vis[nx][ny] = 0;
}
}
int main() {
cin >> n >> m;
// 如果有障碍物,可以预先将 vis[a][b] 置为 1
vis[1][1] = 1; // 必须标记起点
dfs(1, 1);
cout << cnt;
return 0;
}