Maze

Title description

Recently, Little Y is playing a maze game. The game is played on an n*m network. Each grid may be an open space or an obstacle. At the beginning of the game, the player-controlled character is located in a clearing in the picture. During the game, the player can use the up, down, left, and right keys to control the character's movement to the adjacent grid without obstacles (of course, the character cannot move outside the map, nor can it move diagonally). The goal of the game is to collect the stars that appear on the map (each star can only be collected once), the more you collect, the higher the score. Little Y has just started a game. Assuming there is no limit to the game time, he wants to know how many stars he can collect at most.

Input format

The first row contains two positive integers n and m, which means that the game map contains n rows and m columns.
Next, an n*m character matrix is ​​given. Each character may be of the following types:
#: indicates that there is an obstacle at the location
. (period): indicates that the location is an open space
*: indicates that the location is an open space and generates A star
S (uppercase): indicates that the location is a clearing, and the player is initially located at this location, ensure that there is only one S in the picture

Output format

A line containing an integer, indicating the maximum number of stars that can be collected

Input sample

4 8
..#...*.
*.#.S#..
######..
.*..#.*.

Sample output

2

data range

For 50% of the data, n, m<=40;
for 100% of the data, 1<=m, m<=200

Main idea

At first glance at the title, I recognized that this is a search template question.
Look at the data again, um, it must be! ! !

First define the direction array (up, down, left, and right)

int fx[4][2]={
    
    0,1,1,0,-1,0,0,-1};

Then enter the data, use a[][] to save, and record the starting point

cin>>c;
if(c=='.')a[i][j]=1;
if(c=='S')x=i,y=j;
if(c=='*')a[i][j]=2;

Finally search and output

void dfs(int x,int y){
    
    
	if(a[x][y]==2)ans++;//找到星星,ans自增
	a[x][y]=0;//走过的点标为0,避免重复判断
	for(int i=0;i<4;i++){
    
    
		int xx=x+fx[i][0],yy=y+fx[i][1];//接下来去的点的x和y
		if(a[xx][yy])dfs(xx,yy);//判断是否为可以走的点
	}
}

return 0; BBBBBBB

Same for BFS

————————————————————————————————————————
AC code

#include<bits/stdc++.h>
using namespace std;
int n,m,a[1001][1001],x,y,ans,fx[4][2]={
    
    0,1,1,0,-1,0,0,-1};char c;
void dfs(int x,int y){
    
    
	if(a[x][y]==2)ans++;
	a[x][y]=0;
	for(int i=0;i<4;i++){
    
    
		int xx=x+fx[i][0],yy=y+fx[i][1];
		if(a[xx][yy])dfs(xx,yy);
	}
}
int main(){
    
    
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	    for(int j=1;j<=m;j++){
    
    
	    	cin>>c;
	    	if(c=='.')a[i][j]=1;
	    	if(c=='S')x=i,y=j;
	    	if(c=='*')a[i][j]=2;
		}
	dfs(x,y);
	cout<<ans;
}

Guess you like

Origin blog.csdn.net/qq_46258139/article/details/112970759