跳到正文

个人记录

搜索-7.25-河东-401-下午-陈

AK_lwh_888约 6 分钟
原文
文章信息与版本

文章信息

发布
2025年7月25日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 6 分钟

版本

  1. v1当前

7.25-河东-401-下午-陈

P1958 上学路线

这道题直接套上搜索模版就可以过。dfsdfs 开始的时候判断是否到学校,x==n y==m表示到学校了,就将方案加一再 return。

然后就继续搜索,要记得回溯。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=25;
int a[N],n,m,q,ans;
bool vis[N][N];
int dx[]={0,1};
int dy[]={1,0};
bool check(int x,int y){
	return (x<=n&&x>=1&&y<=m&&y>=1&&vis[x][y]==false);
}
void dfs(int x,int y){
	if(x==n&&y==m){
		ans++;
		return;
	}
	for(int i=0;i<2;++i){
		int sx=dx[i]+x;
		int sy=dy[i]+y;
		if(check(sx,sy)){
			vis[sx][sy]=true;
			dfs(sx,sy);
			vis[sx][sy]=false;
		}
	}
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	cin>>q;
	while(q--){
		int s,w;
		cin>>s>>w;
		vis[s][w]=true;
	}
	vis[1][1]=true;
	dfs(1,1);
	cout<<ans<<"\n";
	return 0;
}

P1683 入门

这道题是要求最多可以走的路,输入时判断,如果是 # 就要打上标记,如果是 @@ 不仅要打上标记还要记下坐标,然后 dfsdfs 下这个坐标。

因为是求可以走的最多的路,所以开始不用判断就要将走的路数加一。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=25;
int n,m,maxx=0;
char a[N][N];
bool vis[N][N];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
bool check(int x,int y){
	return (x<=n&&x>=1&&y<=m&&y>=1&&vis[x][y]==false);
}
void dfs(int x,int y){
	maxx++;
	for(int i=0;i<4;++i){
		int nx=dx[i]+x;
		int ny=dy[i]+y;
		if(check(nx,ny)){
			vis[nx][ny]=true;
			dfs(nx,ny);
		}
	}
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>m>>n;
	int h,w;
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			cin>>a[i][j];
			if(a[i][j]=='#')vis[i][j]=true;
			if(a[i][j]=='@'){
				vis[i][j]=true;
				h=i,w=j;
			}
		}
	}                                                                 
	dfs(h,w);
	cout<<maxx<<"\n";
	return 0;
}

U587530 迷宫的第一条出路

只要写上模版就可以写出来,注意方向不要搞错,顺序必须是左、上、右、下这四个方向的顺序,这道题的格式也比较复杂。

C++
x=0,-1,0,1
y=-1,0,1,0

这道题要用到 vector 动态数组,因为动态数组可以自动改变大小存储,所以这道题用动态数组。

动态数组的基本用法:

C++
XX.push_back(  );//输入
XX.pop_back(  );//删除

值得一提的是:这道题不需要回溯。

C++
#include<bits/stdc++.h>
using namespace std;
const int M=25;
int n;
char a[M][M];
struct node{
	int xx,yy;
};
vector<node>box;
int dx[]={0,-1,0,1};
int dy[]={-1,0,1,0};
bool vis[M][M];
bool check(int x,int y){
	return (x<=n&&x>=1&&y>=1&&y<=n&&vis[x][y]==false);
}
void print(){
	cout<<"(1,1)";
	for(int i=0;i<box.size();++i){
		cout<<"->("<<box[i].xx<<","<<box[i].yy<<")";
	}
	cout<<"\n";
//	len=0;
}
bool flag=false;
void dfs(int x,int y){
	if(flag)return;
	if(x==n&&y==n){
		print();
		flag=true;
		return;
	}
//	cout<<x<<","<<y<<"\n";
	for(int i=0;i<4;++i){
		int nx=dx[i]+x;
		int ny=dy[i]+y;
		if(check(nx,ny)){
			vis[nx][ny]=true;
			box.push_back({nx,ny});
			dfs(nx,ny);
			box.pop_back();
		}
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;++i){
		for(int j=1;j<=n;++j){
			cin>>a[i][j];
			if(a[i][j]=='1')vis[i][j]=true;
		}
	}
	vis[1][1]=true;
	dfs(1,1);
	return 0;
}
原文