【发布时间】:2014-06-08 23:31:46
【问题描述】:
当我尝试使用深度优先搜索算法解决问题时,我正在尝试打印出迷宫的坐标,但是,它会打印出初始位置,但会出现故障。有什么我做错了吗???这是我的代码:
#include "mazegen.h"
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define BUFFERSIZE 500
#define FLAG
void mazeSolution(char maze[100][100], int counter, int counter2)
{
stack*currentCell;
int i;
int j;
currentCell = create();
for(i=0; i<counter; i++)
{
for(j=0; j<counter2; j++)
{
if(maze[i][j] == 'S')
{
push(currentCell,i,j);
currentCell->visited = true;
}
}
}
printStack(currentCell);
while(currentCell != NULL)
{
pop(currentCell);
if(maze[i][j] == 'F')
{
break;
}
if(i != 0)
{
if(maze[i-1][j] == ' ' && currentCell->visited != true)
{
currentCell->visited = true;
push(currentCell,i-1,j);
}
}
if(maze[i+1][j] == ' ' && currentCell->visited != true)
{
currentCell->visited = true;
push(currentCell,i+1,j);
}
if(j != 0)
{
if(maze[i][j-1] == ' ' && currentCell->visited != true)
{
currentCell->visited = true;
push(currentCell, i,j-1);
}
}
if(maze[i][j+1] == ' ' && currentCell->visited != true)
{
currentCell->visited = true;
push(currentCell, i, j+1);
}
}
printf("No solution\n");
printStack(currentCell);
}
我认为这与我的 pop 功能以及我实现它的方式有关
void pop (stack*theStack)
{
node*theHead;
if(theStack == NULL)
{
printf("Empty Stack. Error\n");
exit(0);
}
theHead = removeFromFront(theStack->list);
theStack->list = theHead;
}
node*removeFromFront(node*theList)
{
node*temp;
temp = theList->next;
if(temp == NULL)
{
printf("pop Error\n");
return NULL;
}
theList = theList->next;
return theList;
}.
【问题讨论】:
-
你调试过你的代码吗?它在哪一行产生段错误?
-
我已经注释掉了 if 语句,所以它会打印出第一个节点,然后它会出现一个错误,然后它会立即出现 sefgaults
-
向我们展示
pop函数的代码 -
你似乎从不检查 i+1 或 j+1 是否有效?
-
您定义了BUFFERSIZE,但没有显示它的用途。您认为问题出在 pop 函数中,但您没有显示其实现。您如何想象我们会帮助您,我们会猜出您的整个代码吗?顺便说一句,迷宫大小 100 x 100 会产生 2,500 到 10000 个细胞,具体取决于迷宫的表示形式。您确定 500 项缓冲区就足够了吗?