分享一个用递归走迷宫的例子
[C++] 纯文本查看 复制代码 #include<iostream>
using namespace std;
char arr[][17] = {
"011111111111110@",
"0000000000000001",
"1111101111011001",
"0111111111000101",
"1100100000010101",
"11$0001011110001",
"1111111111111111",
};
void test()
{
for (int i = 0; i < 7; i++)
{
for (int n = 0; n < 17; n++)
{
cout << arr[i][n];
}
cout << endl;
}
}
void maze(int x, int y)
{
system("cls");
test();
if (arr[x][y] == '$')
{
cout << "成功!" << endl;
system("pause");
exit(0);
}
arr[x][y] = '?';
if (arr[x][y + 1] == '0' || arr[x][y + 1] == '$')
{
maze(x, y + 1);
};
if (arr[x - 1][y] == '0' || arr[x - 1][y] == '$')
{
maze(x - 1, y);
};
if (arr[x + 1][y] == '0' || arr[x + 1][y] == '$')
{
maze(x + 1, y);
};
if (arr[x][y - 1] == '0' || arr[x][y - 1] == '$')
{
maze(x, y - 1);
};
arr[x][y] = 'Q';
return;
}
int main(void)
{
test();
int x = 0;
int y = 0;
maze(x, y);
return 0;
}
大家觉得如何,嘿嘿。 |