Breadth-First algorithm:
Analog queue: Small amount of data, need to print path coordinates
STL Queue: A large amount of data, only the number of steps to print
Maze problem
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)
1#include <stdio.h>2#include <iostream>3 4 using namespacestd;5 6 Const intMAX =5;7 Const intX[] = {-1,0,1,0 };8 Const intY[] = {0,1,0, -1 };9 Ten struct Point One { A intx, y, pre; - Point () {}; -Pointint_x,int_y,int_pre): X (_x), Y (_y), pre (_pre) {}; the }; - -Point Que[max *MAX]; - intArr[max][max]; + BOOLVis[max][max]; - + voidBFS (); A voidPrint (intn); at - intMain () - { - #ifdef OFFLINE -Freopen ("Input.txt","R", stdin); -Freopen ("output.txt","W", stdout); in #endif - tomemset (que,0,sizeof(que)); +memset (arr,0,sizeof(arr)); -memset (Vis,0,sizeof(Vis)); the * for(inti =0; i < MAX; i++) $ {Panax Notoginseng for(intj =0; J < MAX; J + +) - { thescanf"%d", &arr[i][j]); + } A } the + BFS (); - $ return 0; $ } - - voidBFS () the { - intQH =0, QT =0;Wuyique[qt++] = Point (0,0, -1); thevis[0][0] =true; - Wu while(QH <qt) - { About if(que[qh].x = =4&& Que[qh].y = =4) $ { - Print (QH); - return; - } A + for(inti =0; I <4; i++) the { - intNX = que[qh].x + x[i], NY = que[qh].y + y[i], Npre =QH; $ if(NX >=0&& NX < MAX && NY >=0&& NY < MAX &&!arr[nx][ny] &&!Vis[nx][ny]) the { theque[qt++] =Point (NX, NY, NPRE); theVis[nx][ny] =true; the } - } in theqh++; the } About the return; the } the + voidPrint (intN) - { the if(n = =-1)return;Bayi Print (que[n].pre); theprintf"(%d,%d) \ n", que[n].x, que[n].y); the}View Code
Breadth-First algorithm: Maze problem