Description
Define a two-dimensional array:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
It represents a maze, of which 1 represents a wall, 0 means that the road can be walked, can only walk sideways or vertical walk, can not be inclined to walk, asked to compile the program to find the shortest route from the upper left to the lower right corner.
Input
A 5x5 two-dimensional array that represents a maze. The data guarantee has a unique solution.
Output
The shortest path in the upper-left corner to the lower-right corner, formatted as shown in the sample.
Sample Input
0 1 0 0 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
Analysis:
This is titled A maze, from the upper left to the bottom right through the shortest route, the typical BFS problem first arrived on the exit is mainly the print route can be a value to save the shortest route through
AC Code:
#include <iostream>#include<cstring>using namespacestd;inttop =-1, under =0, visit[ -][2],dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}},queue[ -],a[5][5],v,s[ -];voidQueue_push (intx) {queue[++top] =x;}intQueue_pop () {returnqueue[under++];}intMain () {inti,j; for(i =0; I <5; i++) { for(j =0; J <5; J + +) {cin>>A[i][j]; }} memset (visit,0,sizeof(visit)); Queue_push (0); visit[0][0] =1; while(under<=top) {v=Queue_pop (); if(v = = -) Break; intx = v/5, y = v%5; for(inti =0; I <4; i++) { intPX = x+dir[i][0],py = y +dir[i][1]; if(visit[px*5+py][0] ==0&&a[px][py] = =0&&px>=0&&px<5&&py>=0&&py<5) {Queue_push (px*5+py); satisfies the condition to add into the array visit[px*5+py][0] =1; Mark has passed this point visit[px*5+py][1] =v; Save route} }} for(i =1, s[0] = -; s[i-1] !=0; i++) {S[i]= visit[s[i-1]][1]; } for(j = i1; J >=0; j--) {cout<<"("<<s[j]/5<<", "<<s[j]%5<<")"<<Endl; } return 0;}
2016HUAS Summer Camp 1 J-Maze problem