暑假学习日志————DFS

就三题,不能再多了,贪多嚼不烂

题目1:红与黑

#include <bits/stdc++.h>
using namespace std;
int W,H;
char mp[30][30];
bool vis[30][30];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int step=0;
bool check(int x,int y) {
	if(x>0&&x<=W&&y>0&&y<=H&&vis[x][y]==false&&mp[x][y]=='.'){
		return true;
	}
	else return false ;
}
void dfs(int x,int y){
	if(vis[x][y]) return ;
	vis[x][y]=true;
	step++;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(check(nx,ny)){
			dfs(nx,ny);
		}
	}
}
int main(){
	cin>>W>>H;
	for(int i=1;i<=W;i++){
		for(int j=1;j<=H;j++){
			cin>>mp[i][j];
		}
	}
	for(int i=1;i<=W;i++){
		for(int j=1;j<=H;j++){
			if(mp[i][j]=='@'){
				dfs(i,j);
			}
		}
	}
	cout<<step;

	return 0;
}

题目二:迷宫的第一条出路

#include <bits/stdc++.h>
using namespace std;
const int N=50;
int n;
char mp[N][N];
bool vis[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};

struct way{
	int start;
	int end;
}b[100];

bool check(int x,int y){
	if(x>0&&y>0&&x<=n&&y<=n&&!vis[x][y]&&mp[x][y]=='0'){
		return true;
	}
	else return false ;
}
void dfs(int x,int y,int step){
	step++;
	b[step].start=x;
	b[step].end=y;

	if (x == n && y == n) {
			cout<<"("<<1<<","<<1<<")";
			for(int i=3;i<=step;i++){
				 cout<<"->"<<"("<<b[i].start<<","<<b[i].end<<")";
			}
			
		}
	if(vis[x][y]) return ;
	vis[x][y]=true;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(check(nx,ny)){
			 dfs(nx,ny,step);
		}
	}
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>mp[i][j];
		}
	}
	dfs(1,1,1);
	return 0;
}

题目三:迷宫的路径?

#include <bits/stdc++.h>
using namespace std;
const int N=50;
int n,m,flag;
char mp[N][N];
bool vis[N][N];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

struct way{
	int start;
	int end;
}b[100];
int ans = 0;
bool check(int x,int y){
	if(x>0&&y>0&&x<=n&&y<=m&&!vis[x][y]&&mp[x][y]=='o'){
		return true;
	}
	else return false ;
}
void dfs(int x,int y,int step){
	step++;
	b[step].start=x;
	b[step].end=y;
	
	if (x == n && y == m) {
		flag=1;
		ans++;
		cout<<ans<<':';
		cout<<1<<","<<1;
		for(int i=3;i<=step;i++){
			cout<<"->"<<b[i].start<<","<<b[i].end;
		}
		cout<<endl;
	}
	
	vis[x][y]=true;
	for(int i=0;i<4;i++){
		int nx=x+dx[i];
		int ny=y+dy[i];
		if(check(nx,ny)){
			dfs(nx,ny,step);
		}
	}
	vis[x][y]=0;
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>mp[i][j];
		}
	}
	
	dfs(1,1,1);
	if(!flag)
		cout<<"no"<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值