2021 Niu Guest Winter Holiday Algorithm Basic Training Camp 6 I. Snake

I. Snakes

Title link: https://ac.nowcoder.com/acm/contest/9986/I

Title description:

Infinitely growing snake game:

In a maze of n*m, there is a small snake. There are many walls on the map. The wretched questioner is represented by "#", and the path that can be taken is represented by ".". The snake was born at a random spot. In the upper part, the spawn point is represented as "S", and the end point he wants to reach is represented as "E". The little snake has a strange ability. Every time he walks, it increases by one. That is, after he walks one square, his The tail will not retract.

Little snake wants to know how he gets where he wants to go, please help him.

PS: Each grid is 1 meter long. Snakes are not allowed to hit the wall or bite their own body.

Enter a description:

The first line: input N, M;

Second line: Enter the coordinates Xs, Ys of S, and Xe, Ye of E;

The next N lines:

Enter M numbers for each line to describe the situation of each line.

Output description:

Output a number, the shortest distance for the snake to reach the end point (unit: cm), if it cannot be reached, output -1

Example 1:

Input
3 3
1 1 3 3
.#.
.#.

output
400

Example 2:

Input
5 5
1 1 5 5
…###
.#…
.#.#.
.#.#.
…#.
Output
1400
Note:
For 100% data: 1≤n,m≤100, ensure that the starting point is not a fence.

Problem-solving ideas:

From the start point to the end point, bfs search for the shortest path, pay attention to the conversion of the hexadecimal system (multiply the final result by 100)

code show as below:

#include <iostream>
#include<queue>
using namespace std;
const int INF = 10005;
typedef pair<int,int> PA; 
char maze[105][105];
int n,m;  
int sx,sy;  //开始位置坐标
int gx,gy;   //结束位置坐标
int d[105][105];
int dx[4]={
    
    1,0,-1,0},dy[4]={
    
    0,1,0,-1};  //移动
int bfs(){
    
    
	queue<PA> que;
	for (int i = 0; i < n; i++) 
		for (int j = 0; j <m; j++) 
			d[i][j] = INF;  //初始化
	que.push(PA(sx,sy));
	d[sx][sy]=0;
	while(que.size()){
    
    
		PA p=que.front();
		que.pop();
		if(p.first==gx&&p.second==gy) break; 
		for(int i=0;i<4;i++){
    
    
			int nx=p.first+dx[i];
			int ny=p.second+dy[i];		
			if(nx>=0&&nx<n&&ny>=0&&ny<m  //判断边界
				&&maze[nx][ny]!='#'&&d[nx][ny]==INF){
    
      //判断可移动&没走过
					que.push(PA(nx,ny));
					d[nx][ny]=d[p.first][p.second]+1; 
			} 
		}
	}
	return d[gx][gy];	
} 
int main(){
    
    
	scanf("%d%d",&n,&m);
	scanf("%d%d%d%d",&sx,&sy,&gx,&gy);
	for(int i=0;i<n;i++){
    
    
		scanf("%s",maze[i]);
	}
	sx--, sy--, gx--, gy--;
	int ans = bfs();
	if(ans!=INF)
		printf("%d\n",ans*100);
	else
		printf("-1\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/114034469