迷宫走法(基于DFS)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*
测试数据
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3

7
*/
int n,m,min=9999999;
int px,py;
int a[51][51],book[51][51];
void dfs(int x,int y,int step)
{
	int next[4][2]={
   
   {0,1},{1,0},{0,-1},{-1,0}};
	if(x==px && y==py){
		if(step<min)
			min=step;
		return;
	}
	int tx,ty;
	for(int k =0;k<=3;k++){
		tx = x + next[k][0];
		ty = y + next[k][1];
		if(tx<1 || tx>n || ty<1 || ty>m)
			continue;
		if(a[tx][ty]==0 && book[tx][ty]==0){
			book[tx][ty] = 1;
			dfs(tx,ty,step+1);
			book[tx][ty]=0;
		}
	}
	return;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i = 1;i<=n;i++){
		for(int j = 1;j<=m;j++)
		scanf("%d",&a[i][j]);
	}
	int startx,starty;
	scanf("%d %d %d %d",&startx,&starty,&px,&py);
	book[startx][starty]=1;
	dfs(startx,starty,0);
	printf("%d\n",min);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_49019274/article/details/114857969
今日推荐