玩具蛇-dfs

本文介绍了一种使用深度优先搜索(DFS)算法在4x4网格中解决玩具蛇游戏路径标记的问题,包括从起点开始遍历并标记所有可到达的位置,最后输出可达区域的数量。
摘要由CSDN通过智能技术生成

0玩具蛇 - 蓝桥云课 (lanqiao.cn)

dfs打访没访问过的标记时,要记得起点(初始点)也得标记

#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
bool vis[4][4];
int res;
int move_hang[4]={-1,0,1,0},move_lie[4]={0,1,0,-1};
bool dfs(int x,int y,int index){
	if(index==16){
		res++;
		return true;
	}
	for(int i=0;i<4;i++){
		int xx=x+move_hang[i];
		int yy=y+move_lie[i];
		if(xx<0||yy<0||xx>=4||yy>=4) continue;
		if(vis[xx][yy]) continue;
		vis[xx][yy]=true;
		dfs(xx,yy,index+1);
		vis[xx][yy]=false;
	}
	return false;
}
void solve(){
	for(int i=0;i<4;i++){
		for(int j=0;j<4;j++){
			memset(vis,false,sizeof(vis));
			//不要忘了第一个点,即起点也要标记
			vis[i][j]=true;
			dfs(i,j,1);
		}
	}
	cout<<res;
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();
	return 0;
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值