在运行迷宫问题(八个方向可走)时,vs报错出现访问冲突,多次调试也没有办法😫
报错如下:
这是我的算法:
调试过程:
以下是完整代码:
#include
#include"string.h"
using namespace std;
const int M = 10;
const int N = 10;
int m[M][N] = {
(1,1,1,1,1,1,1,1,1,1),
(1,0,0,1,1,0,0,1,1,1),
(1,0,0,1,1,1,0,0,0,1),
(1,0,0,0,1,1,0,0,1,1),
(1,0,1,0,1,1,0,0,1,1),
(1,0,1,0,0,1,1,0,1,1),
(1,0,1,0,0,0,1,0,1,1),
(1,1,1,0,0,1,0,0,0,1),
(1,1,0,0,0,0,0,0,1,1),
(1,1,1,1,1,1,1,1,1,1)
};
typedef struct BOX{
int x=0,y=0;
int dir=1;
bool de=true;
}BOX;
BOX nextstep(BOX a) {
if (a.dir == 1) {
a.x--;
a.y--;
}
if (a.dir == 2) {
a.y--;
}
if (a.dir == 3) {
a.x++;
a.y--;
}
if (a.dir == 4) {
a.x++;
}
if (a.dir == 5) {
a.x++;
a.y--;
}
if (a.dir == 6) {
a.y--;
}
if (a.dir == 7) {
a.x--;
a.y++;
}
if (a.dir == 8) {
a.x--;
}
return a;
}
typedef struct {
BOX* top;
BOX* base;
int size;
}path;
void creatpath(path& a) {
a.base = new BOX;
a.top = a.base;
a.size = 0;
}
void push(path& a,BOX ox) {
if (a.top - a.base >= a.size) {
path b;
b.base = new BOX[a.size + 1];
BOX* p1=a.base,*p2=b.base ;
while (p1!=a.top ) {
*p2 = *p1;
p2++;
p1++;
}
*p2 = ox;
delete a.base;
a.size++;
a.base = b.base ;
a.top = a.base + a.size;
}
*a.top++ = ox;
}
bool pop(path& a,BOX &ox) {
if (a.top = a.base) {
return false;
}
a.top--;
ox = *a.top;
return true;
}
BOX Gettop(path a) {
a.top--;
BOX b = *a.top;
return b;
}
path findway( BOX start, BOX out) {
path way;
creatpath(way);//创建路线
push(way, start);//把起点压入路线
m[1][1] = 1;
BOX next,cur;
while (cur.x !=out.x &&cur.y!=out.y) {
cur = Gettop(way);//取得当前所在位置
next = nextstep(cur);//取得下一步位置
if (m[next.x][next.y] == 0) {//若下一位置能走
m[next.x][next.y] = 1;//标记下一个位置已经走过
push(way, next);//把下一个位置压入路线
if (next.x == out.x && next.y == out.y)
{
return way;
}//若走出迷宫返回路线
continue;//继续循环
}
if (m[next.x][next.y] == 1) {//若下一位置不能走
cur.dir++;//改变方向
if (cur.dir > 8) {//若四周都不能走
m[cur.x][cur.y] = 1;//标记当前位置不能走
pop(way,cur);//回退一格
}
}
}
}
void deletepath(path& way) {
delete way.base;
}
int main()
{
BOX start;
start.x = 1;
start.y = 1;
BOX out;
out.x = 5;
out.y = 1;
path v = findway(start, out);
BOX *p=v.base ;
while(p != v.top) {
cout << "(" << p->x << "," << p->y << "<" << ")" << "\n";
p++;
}
deletepath (v);
}
请大家帮忙看看!非常感谢!