A. Problem description: Define a two-dimensional array, as follows:
int Maze[max_row][max_col] = {
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 in which 1 represents a wall, and 0 indicates a walking path, which can only be walked horizontally or vertically, not sideways.
Requirements (1): Output from upper left corner to lower right corner of a line
(2) Output all routes from upper left to lower right corner
Reprint please specify the source: landscape between the blog: http://blog.csdn.net/linyanwen99/article/details/8235223
Two. requirements (1) are implemented as follows, and the code is concise, without repeating:
#include <stdio.h>
#define Max_row 5
#define MAX_COL 5
struct point{
int row;
int col;
}STACK[512];
int top = 0;
void push (struct point p) {
Stack[top] = p;
top++;
}
struct point pop () {
top--;
return stack[top];
}
BOOL IsEmpty () {
return top = 0;
}
int Maze[max_row][max_col] = {
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
};
void Printmaze () {
for (int i=0;i<max_row;++i) {
for (int j=0;j<max_col;++j) {
printf ("%d", maze[i][j]);
}
printf ("\ n");
}
printf ("*********\n");
}
/**
* Here you need to define a two-dimensional array of precursors, and are initialized to-1, used to represent the visited nodes, where omitted
*/
void visit (int row,int col,struct point pre) {
struct point visitpoint = {Row,col};
Maze[row][col] = 2;
Predecessor[row][col] = Pre;//predecessor is an array of precursors, as described above
Push (Visitpoint);
}
int main (int argc,char** argv) {
struct point P = {0,0};
struct Point pp = {0,0};
Maze[p.row][p.col] = 2;
Push (P);
while (!isempty ()) {
p = Pop ();
if (P.row = = Max_row-1 && P.col = = max_col-1) {
if (!isempty ()) {
printf ("Stack is not empty\n");
pp = pop ();
printf ("Now"%d,%d\n, Pp.row,pp.col);
}
Break
}
if (P.col+1 < Max_col && maze[p.row][p.col+1] = 0) {
printf ("right\n");
Visit (P.ROW,P.COL+1,P);
}
if (P.row+1 < Max_row && Maze[p.row+1][p.col] = 0) {
printf ("up\n");
Visit (P.ROW+1,P.COL,P);
}
if (p.col-1 >= 0 && maze[p.row][p.col-1] = = 0) {
printf ("left\n");
Visit (P.ROW,P.COL-1,P);
}
if (p.row-1 >= 0 && maze[p.row-1][p.col] = = 0) {
printf ("down\n");
Visit (P.ROW-1,P.COL,P);
}
Printmaze ();
}
if (P.row = = Max_row-1 && P.col = = max_col-1) {
printf ("(%d,%d) \ n", P.row,p.col);
while (Predecessor[p.row][p.col].row!=-1) {
p = Predecessor[p.row][p.col];
printf ("(%d,%d) \ n", P.row,p.col);
}
}else{
printf ("No path\n");
}
return 0;
}
Three. Requirements (2) need to output all the routes, just a slight modification on the basis of the previous, you can achieve, here omitted.
References: Song Jingbin, Linux C programming one-stop learning
Reprint please specify the source: landscape between the blog: http://blog.csdn.net/linyanwen99/article/details/8235223