题解:把图放大3倍,这样路就出来了,接着只需要向4个方向遍历即可。 如果遍历时超过边界则说明不能构成回路。
#include <cstdio>
#include <cstring>
char data[80][80], maze[240][240];
int row, column, flag, step, dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool find_cycle(int x, int y) {
if (x < 0 || x == 3 * row || y < 0 || y == 3 * column) //如果越界,就说明不能构造回路 则 flag = 0
return flag = 0;
if (maze[x][y] == 1) //如果已来过,就返回
return false;
maze[x][y] = 1; //标记已来过
step++;
for (int i = 0; i < 4; i++) //由该位置向 4 个方向遍历迷宫
find_cycle(x + dir[i][0], y + dir[i][1]);
return flag;
}
int main () {
int t = 0;
while (scanf("%d%d", &column, &row), column) {
for (int i = 0; i < row && scanf("%s", data[i]); i++);
int max = 0 , count = 0;
memset(maze, 0, sizeof(maze));
for (int i = 0; i < row; i++) //构造迷宫
for (int j = 0; j < column; j++)
if (data[i][j] == '\\')
maze[i * 3][j * 3] = maze[i * 3 + 1][j * 3 + 1] = maze[i * 3 + 2][j * 3 + 2] = 1;
else
maze[i * 3 + 2][j * 3] = maze[i * 3+ 1][j * 3 + 1] = maze[i * 3][j * 3 + 2] = 1;
for (int i = 0; i < 3 * row; i++) //寻找回路
for (int j = 0; j < 3 * column; j++) {
flag = 1, step = 0;
if (find_cycle(i, j))
count++, max = (step > max ? step : max);
}
printf("Maze #%d:\n", ++t);
count ? printf("%d Cycles; the longest has length %d.\n\n", count, max/3) : printf("There are no cycles.\n\n");
}
return 0;
}