week4 dfs

模板
 

void dfs(int step)
{
        判断边界
        {
            相应操作
        }
        尝试每一种可能
        {
               满足check条件
               标记
               继续下一步dfs(step+1)
               恢复初始状态(回溯的时候要用到)
        }

例题·1

#include<bits/stdc++.h>
using namespace std;
const int maxn=10;
bool flag[maxn][maxn];//可走 
bool visited[maxn][maxn];//走过 
int qx,qy,lx,ly;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};//如何走 
int ans=0;//方案数 
void dfs(int nowx,int nowy) 
{
	if(nowx==lx&&nowy==ly) 
	{
		ans=ans+1;
		return;
	}//判断 
	 for(int i=0;i<4;i++)
    {
    	 int  nowx1=nowx+dx[i];
    	 int nowy1=nowy+dy[i];//修改操作 
    	if(visited[nowx1][nowy1]==0&&flag[nowx1][nowy1]==1)
    	{
    		visited[nowx1][nowy1]=1;//标记 
    		dfs(nowx1,nowy1);
    		visited[nowx1][nowy1]=0; //回溯 
		}
	}

	return;
}

int main()
{
	int n,m,t;
	cin>>n>>m>>t;
	cin>>qx>>qy>>lx>>ly;
	for(int i=1;i<=n;i++)
       for(int j=1;j<=m;j++)
	      flag[i][j]=1;
		

    for(int i=0;i<t;i++)
    {
    	int k,j;
    	cin>>k>>j;
    	flag[k][j]=0;
   	}
    visited[qx][qy]=1;
    dfs(qx,qy);
    cout<<ans;
    return 0;
}

例题2

#include<bits/stdc++.h>
using namespace std;
const int maxn=404;
int dx[8]={1,1,-1,-1,2,2,-2,-2,};
int dy[8]={2,-2,2,-2,-1,1,-1,1};//如何走 
int step[maxn][maxn];//步数 
int n,m,x,y;


void dfs(int nowx,int nowy,int nowstep) 
{
	if(nowstep>400) return;//边界 
	if(nowx<1||nowx>n||nowy<1||nowy>m) return;//边界 
	if(step[nowx][nowy]<=nowstep&&step[nowx][nowy]!=-1) return;
	step[nowx][nowy]=nowstep;//更新 
	    for(int i=0;i<8;i++){
         
            dfs(nowx+dx[i],nowy+dy[i],nowstep+1);//不需要回溯 
        }
    
}



int main()
{
	cin>>n>>m>>x>>y;

	for(int i=1;i<=n;i++)
	for(int j=1;j<=m;j++)
	step[i][j]=-1;
    dfs(x,y,0);
	for(int i=1;i<=n;i++)
	{for(int j=1;j<=m;j++)
      cout<<step[i][j]<<" ";
	  cout<<endl;
	}
	return 0;
}

the key

定义一个阈值  如400(考虑 n,m的值)

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值