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

Question two:

Given a map, how many paths are there to get from one point to another?

Take (0,0) as the starting point, # as the obstacle, and T as the end point

#include<bits/stdc++.h>
using namespace std;
string maze[100];
int val[100][100]={0};
int fx[4][2]={
   
   {0,1},{-1,0},{0,-1},{1,0}}; // 右,上,左,下  逆时针   x为y坐标,y为x坐标。(因为x代表行,y代表列)

bool panduan(int x,int y,int n,int m)
{
	return 0<=x&&x<n&&0<=y&&y<m;
	
}

void dfs(int x,int y,int &ans,int n,int m)
{
    if(maze[x][y]=='T')
	{
		ans++;
		return;
		}	
		
	val[x][y]=1;	
	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,ans,n,m);
		}
		}
		
	val[x][y]=0;
}
int main()
{
	int n,m;
	cin>>n>>m;
	int ans =0;
	for(int i=0;i<n;i++)
	{
		cin>>maze[i];
	}
	
	int x=0,y=0;
	dfs(x,y,ans,n,m);
    
    cout<<ans<<endl;
	
	return 0;
}

Result demo:

 

 

Guess you like

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