【发布时间】:2016-08-16 01:31:49
【问题描述】:
问题
我是这种编程的新手,我的 C++ 迷宫求解器陷入了循环。
迷宫是一个简单的 char 二维矩阵,星号 (*) 表示有效路径方块,斜线 (/) 表示墙壁方块。
为什么程序找到'/'时不停止?
# include < iostream >
using namespace std;
char lab[6][6] =
{ { '/','/','/','/','/' },
{ '/','*','/','/','/' },
{ '/','*','*','*','/' },
{ '/','/','*','/','/' },
{ '/','/','*','/','/' },
{ '/','/','*','*','*' } };
int x, y;
void run(char lab[][6], int, int);
bool movU() // Move Up
{
if (lab[x][y - 1] == '*')
return true;
else
return false;
}
bool movR() // Move right
{
if (lab[x + 1][y] == '*')
return true;
else
return false;
}
bool movD() // Move Down
{
if (lab[x][y + 1] == '*')
return true;
else
return false;
}
bool movL() // Move Left
{
if (lab[x - 1][y] == '*')
return true;
else
return false;
}
void run(char lab[][6], int x, int y)
{
if (movU() == true) // I'm getting stuck right here
run(lab, x, y - 1); // Getting negative numbers here
else if (movR() == true)
run(lab, x + 1, y);
else if (movD() == true)
run(lab, x, y + 1);
else if (movL() == true)
run(lab, x - 1, y);
else
cout << "Error" << endl;
}
int main()
{
x = 1, y = 2; // Start position
run(lab, x, y);
return 0;
}
【问题讨论】:
-
movU()使用全局x、y(均未初始化)。将movU()更改为movU(int x, int y)等,然后在run中执行if (movU(x, y) == true)等 -
谢谢!现在可以了,我没想过要这样做,我需要多加注意
标签: c++ recursion infinite-loop