여기 내 코드가 있습니다.while 루프로 반복적으로 코딩하는 부분을 변경하려고합니다.
#include <iostream>
using namespace std;
enum Direction { EAST, NORTH, WEST, SOUTH };
const int size = 12;
int xStart = 2; int yStart = 0;
char *maze2[ ] = {
"############",
"#...#......#",
"..#.#.####.#",
"###.#....#.#",
"#....###.#..",
"####.#.#.#.#",
"#..#.#.#.#.#",
"##.#.#.#.#.#",
"#........#.#",
"######.###.#",
"#......#...#",
"############",
};
void printMaze (char maze[][ size ]);
void mazeTraverse(char maze[][ size ], int x, int y, int direction);
int main()
{
char maze[ size ][ size ];
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
maze[ x ][ y ] = maze2[ x ][ y ];
printMaze(maze);
mazeTraverse(maze, xStart, yStart, EAST);
}
void printMaze (char maze[][ size ])
{
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
cout << maze[ x ][ y ];
cout << endl;
}
cout << endl;
cout << "\nHit return to see next move\n";
cin.get();
}
bool validMove(char maze[][ size ], int x, int y)
{
return x >= 0 && x < size && y >= 0 && y < size && maze[x][y] != '#';
}
bool coordsAreEdge(int x, int y)
{
return x== 0 || x== size - 1 || y == 0 || y== size - 1;
}
void mazeTraverse(char maze[][ size ], int x, int y, int direction)
{
maze[ x ][ y ] = 'x';
printMaze(maze);
if (coordsAreEdge(x, y) && (x != xStart || y!= yStart))
{
cout <<"\nMaze successfully exited!\n\n";
return;
}else{
for (int move = direction, count = 0; count < 4;
count++, move++, move %=4)
{
int nextX; int nextY;
switch (move)
{
case SOUTH: nextX = x + 1; nextY = y; break;
case EAST: nextX = x; nextY = y + 1; break;
case NORTH: nextX = x - 1; nextY = y; break;
case WEST: nextX = x; nextY = y - 1; break;
default: ;
}
if (validMove(maze, nextX, nextY))
{
//Recursion move part 1
//mazeTraverse (maze, nextX , nextY, (move + 3)%4);
return;
}
}
}
}
나는 회귀 대신 mazeTraverse 함수를 while 루프로 만들려고 노력 중이며 막혔다.
재귀 버전의'if (validMove' 부분) 안에'return' 문이 있습니까? –