Three questions, let you quickly start dfs (third question)

Question three:

Given a map, ask how long is the shortest path among all paths from one point to another

# is the obstacle, T is the end point

The input format is (the number of each point on the map represents the distance)

Such as: int n,m; //n row, m column

Input: 3   3

 1 2 3

4 # 6 

7 8 T

The map is this 3*3 array, and the number is the number of steps that need to be taken

#include<bits/stdc++.h>
using namespace std;
vector<int> path;

string maze[100];
int fx[4][2]={
   
   {0,1},{-1,0},{0,-1},{1,0}};
bool panduan(int x,int y,int n,int m)
{
	return 0<=x&&x<n&&0<=y&&y<m;
}

int val[100][100]={0};

void dfs(int x,int y,int sum,int n,int m)
{
	if(maze[x][y]=='T')
	{
		path.push_back(sum);
		return;
	}
	
	val[x][y]=1;
	sum+=(maze[x][y]-'0');
	for(int i=0;i<4;i++)
	{
		int tx = x+fx[i][0];
		int ty = y+fx[i][1];
		
		if(panduan(tx,ty,n,m)&&maze[tx][ty]!='#'&&val[tx][ty]!=1)
		{
			dfs(tx,ty,sum,n,m);
		}
	}
	val[x][y]=0;
	sum-=(maze[x][y]-'0');
	
}

int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
	  cin>>maze[i];
	}
	
	int x=0,y=0;
	int sum=0;

	dfs(x,y,sum,n,m);
	
	sort(path.begin(),path.end());
	
	cout<<path[0];
}

Result demo:

 

Guess you like

Origin blog.csdn.net/qq_58136559/article/details/129627486