【深度优先搜索】计蒜客:Betsy的旅行_#include

DFS:起点到终点,如果到终点时正好走了n*n步,ans++;

如果不剪枝,会超时

剪枝:

1、避免走入死胡同

【深度优先搜索】计蒜客:Betsy的旅行_#include_02

2、避免形成孤立的区域

【深度优先搜索】计蒜客:Betsy的旅行_ios_03

代码:

#include<iostream>
using namespace std;
int n;
int ans=0;
bool vis[8][8];

void dfs(int x,int y,int step){
	if(!(x>=0&&y>=0&&x<n&&y<n))return;
	if(vis[x][y]==true)return;
	if(x==n-1&&y==0){
		if(step==n*n-1){
			ans++;
		}
		return;
	}
	if(x==n-1&&vis[x][y+1]==false&&vis[x][y-1]==false&&y-1>=0&&y+1<n||y==n-1&&vis[x+1][y]==false&&vis[x-1][y]==false&&x-1>=0&&x+1<n){
		return;
	}
	vis[x][y]=true; 
	dfs(x+1,y,step+1);
	dfs(x-1,y,step+1);
	dfs(x,y+1,step+1);
	dfs(x,y-1,step+1);
	vis[x][y]=false;
	
}
int main(){
	cin>>n;
	dfs(0,0,0);
	cout<<ans;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

 经验:缩小范围,用好调试