开始无从下手,后来参考了别人的思路 http://blog.csdn.net/shuangde800/article/details/7726620
有了思路后不知道怎么求环,后来发现题目说了没岔路。。
#include<stdio.h> #include<string.h> #define MAX 200 int w, h; char maze[MAX][MAX]; int cases = 1; int isCircle; int num; int circleCount; int maxLen; int hasCircle; int dir[8][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 }, { -1, -1 }, { -1, 1 }, { 1, -1 }, { 1, 1 } }; int pass(int i, int j, int k) { if (k < 4) return 1; int x = i + dir[k][0]; int y = j + dir[k][1]; if (x >= 0 && y >= 0 && maze[x][j] == '\\' && maze[i][y] == '\\' && (k == 5 || k == 6)) return 0; if (x >= 0 && y >= 0 && maze[x][j] == '/' && maze[i][y] == '/' && (k == 4 || k == 7)) return 0; return 1; } void dfs(int i, int j) { if (i < 0 || j < 0 || i >= 2 * h || j >= 2 * w) { isCircle = 0; return; } if (maze[i][j] == '*' || maze[i][j] == '\\' || maze[i][j] == '/') return; maze[i][j] = '*'; num++; int k; for (k = 0; k < 8; k++) { if (pass(i, j, k)) { dfs(i + dir[k][0], j + dir[k][1]); } } } int main() { while (scanf("%d%d", &w, &h) != EOF) { if (w == 0) break; memset(maze, 0, sizeof(maze)); getchar(); int i, j; char ch; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { scanf("%c", &ch); if (ch == '\\') { maze[2 * i][2 * j] = '\\'; maze[2 * i + 1][2 * j + 1] = '\\'; } else if (ch == '/') { maze[2 * i][2 * j + 1] = '/'; maze[2 * i + 1][2 * j] = '/'; } } getchar(); } circleCount = 0; maxLen = -1; hasCircle = 0; for (i = 0; i < 2 * h; i++) for (j = 0; j < 2 * w; j++) { if (maze[i][j] == 0) { num = 0; isCircle = 1; dfs(i, j); if (isCircle && num >= 4) { hasCircle = 1; circleCount++; if (num > maxLen) maxLen = num; } } } printf("Maze #%d:\n", cases++); if (hasCircle) { printf("%d Cycles; the longest has length %d.\n\n", circleCount, maxLen); } else { printf("There are no cycles.\n\n"); } } return 0; }