栈解决迷宫问题?似乎出现了越界的问题?
我写了个迷宫的程序,编译可以通过,但运行时有时提示c0000005错误,似乎是栈越界了,不知道如何解决是好,请大家帮助一下程序代码:
# include <stdio.h> # include <stdlib.h> # define MAX 255 typedef struct Node { //节点类型 int row; //行 int col; //列 int direction; //方向数 }Node; typedef struct //栈指针 { Node *base; Node *top; }Stack; //////////////////////////////////////////////////// void InitStack( Stack &T, int n ) //初始化堆栈 { T.base = ( struct Node * )malloc( n * sizeof ( Node ) ); T.top = T.base; } void Push (Stack &T, int Ti, int Tj) { T.top->row = Ti; T.top->col = Tj; T.top->direction = -1; T.top++; } //////////////////////////////////////////////////// int main() { int Maze[MAX][MAX]; //迷宫数组 int n, minstep = 9999; //迷宫的维数 int i, j, direction, flag; Stack S_Maze, Path, pt; // S_Maze:查找栈; Path最短路径栈 scanf( "%d", &n ); //输入维数 for ( i = 1 ; i <= n ; i++ ) //获取迷宫数据 { for ( j = 1 ; j <= n ; j++ ) scanf("%d", &Maze[i][j] ); } for ( j = 0 ; j <= n+1 ; j++ ) //扩充行边界 { Maze[0][j] = 1; Maze[n+1][j] = 1; } for ( j = 0 ; j <= n+1 ; j++ ) //扩充列边界 { Maze[j][0] = 1; Maze[j][n+1] = 1; } /////////////////////初始化//////////////////// InitStack( S_Maze, n ); InitStack( Path, n ); InitStack( pt, n ); i = j = 1; direction = -1; Push( S_Maze, i , j );//起点进栈 Maze[i][j] = -1; //////////////////////////////////////////////// while ( S_Maze.top != S_Maze.base )//栈不空时循环查找路径 { S_Maze.top--;//top指针指向栈顶元素 direction = S_Maze.top->direction; i = S_Maze.top->row; j = S_Maze.top->col; if ( i == n && j == n ) //到终点了 { if ( S_Maze.top - S_Maze.base < minstep ) {//当前路径更短 minstep = S_Maze.top - S_Maze.base; //记录路径 pt.base = S_Maze.base; S_Maze.top++; pt.top = S_Maze.top; S_Maze.top--; while ( pt.base != pt.top ) { Push( Path, pt.base->row, pt.base->col ); pt.base++; } } Maze[S_Maze.top->row][S_Maze.top->col] = 0; S_Maze.top--;//回到之前节点,相当于完成一次退栈操作 i = S_Maze.top->row; j = S_Maze.top->col; direction = S_Maze.top->direction; } flag = 0;//未找到下一节点 while ( direction < 4 && flag == 0) { direction++; switch ( direction ) { case 0: i = S_Maze.top->row - 1 ; j = S_Maze.top->col ; break;//上 case 1: i = S_Maze.top->row ; j = S_Maze.top->col + 1 ; break;//右 case 2: i = S_Maze.top->row + 1 ; j = S_Maze.top->col ; break;//下 case 3: j = S_Maze.top->row ; j = S_Maze.top->col - 1 ; break;//左 } if ( i >= 0 && j >=0 && Maze[i][j] == 0 ) //判断节点是否可走,防止越界 { flag = 1; } } S_Maze.top++; if ( flag == 1 ) { S_Maze.top--; S_Maze.top->direction = direction;//修改之前节点方向数 S_Maze.top++; Push( S_Maze, i, j );//此节点可走--->进栈 Maze[i][j] = -1; //标志节点走过 } else//无路可走的情况 { S_Maze.top--; if ( S_Maze.top < S_Maze.base ) break; Maze[S_Maze.top->row][S_Maze.top->col] = 0;//恢复节点为0 ////运行到这里就出问题了 S_Maze.top--;//top指针-1,相当于完成一次出栈操作 } } printf("Shortest Path Needs %d Steps\n", minstep); printf("The Path is :\n"); while ( Path.base != Path.top ) { printf("(%d,%d)", Path.base->row, Path.base->col ); Path.base++; } printf("\n"); system("pause"); return (0); }