17
0

简单DFS/深搜(回溯)模板

2026-06-04
#include <bits/stdc++.h>
using namespace std;
inline int read() 
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
inline void write(int x) 
{
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}
int xx[5] = {0,1,-1,0,0},yy[5] = {0,0,0,-1,1};
int n,m,t;
int sx,sy,fx,fy;
int mapp[30][30];
int ma = 0;
void dfs(int x,int y)
{
	if(x == fx && y == fy)
	{
		ma++;
		return;
	}
	for(int i = 1;i <= 4;i++)
	{
		int dx = x + xx[i],dy = y + yy[i];
		if(dx >= 1 && dx <= n && dy >= 1 && dy <= m && mapp[dx][dy] == 0 && mapp[dx][dy] != 2)
		{
			mapp[dx][dy] = 2;
			dfs(dx,dy);
			mapp[dx][dy] = 0;
		}
	}
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> t;
    cin >> sx >> sy >> fx >> fy;
    for(int i = 1;i <= t;i++)
    {
    	int a,b;
    	cin >> a >> b;
    	mapp[a][b] = 1;
	}
	mapp[sx][sy] = 2;
	dfs(sx,sy);
	cout << ma;
    return 0;
}

题目:洛谷P1605

简单DFS/深搜(回溯)模板
/archives/jian-dan-dfs-shen-sou-hui-su-mo-ban
作者
魏熙音
发布于
2026-06-04
许可协议
CC BY-NC-SA 4.0

评论