As you can see, paths in the maze cannot branch, so the whole maze only contains cyclic paths and paths entering somewhere and leaving somewhere else. We are only interested in the cycles. In our example, there are two of them.
Your task is to write a program that counts the cycles and finds the length of the longest one. The length is defined as the number of small squares the cycle consists of (the ones bordered by gray lines in the picture). In this example, the long cycle has length 16 and the short one length 4.
The input contains several maze descriptions. Each description begins with one line containing two integersw and h ( ), the width and the height of the maze. The next h lines represent the maze itself, and contain w characters each; all these characters will be either ``/
" or ``\
".
The input is terminated by a test case beginning with w = h = 0. This case should not be processed.
For each maze, first output the line ``Maze #n:'', where n is the number of the maze. Then, output the line ``kCycles; the longest has length l.'', where k is the number of cycles in the maze and l the length of the longest of the cycles. If the maze does not contain any cycles, output the line ``There are no cycles.".
Output a blank line after each test case.
6 4 \//\\/ \///\/ //\\/\ \/\/// 3 3 /// \// \\\ 0 0
Maze #1: 2 Cycles; the longest has length 16. Maze #2: There are no cycles.
话说这题拖了好长时间了。。刚看的时候没什么思路,就放下了,然后。。就一直放到现在。。。
实在没想出什么好办法,于是忍不住搜了一下各个大牛的题解(罪过罪过。。),发现了个很巧妙的方法,就是放大3倍法,把每一个格子都放大为9个格子的形式,0代表可以走,1代表不可以走。然后简单的用DFS搜就行了。注意由于每3个可以走的格子实际上只是一个格子,所以最终答案应该除以3.这里判断不是回路的办法是是否与外界相连,与外界相连就不是回路。还有,要注意格式啊!!该死的UVa,,,格式不对算WA,又害我WA了好几次。。。代码如下:
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int n, m, ans, flag; int jx[]= {0,0,1,-1}; int jy[]= {1,-1,0,0}; void dfs(int s[300][300], int x, int y) { int i, a, b; for(i=0; i<4; i++) { a=x+jx[i]; b=y+jy[i]; if(a>=0&&a<3*n&&b>=0&&b<3*m) { if(!s[a][b]) { ans++; s[a][b]=1; dfs(s,a,b); } } else flag=0; } } int main() { int i, j, map[300][300], max1, num=0, x; char s[100]; while(scanf("%d%d",&m,&n)!=EOF&&n&&m) { max1=0; num++; x=0; memset(map,0,sizeof(map)); for(i=0; i<n; i++) { scanf("%s",s); for(j=0; j<m; j++) { if(s[j]=='\\') { map[3*i][3*j]=1; map[3*i+1][3*j+1]=1; map[3*i+2][3*j+2]=1; } else { map[3*i][3*j+2]=1; map[3*i+1][3*j+1]=1; map[3*i+2][3*j]=1; } } } for(i=0; i<3*n; i++) { for(j=0; j<3*m; j++) { if(map[i][j]==0) { flag=1; ans=0; dfs(map,i,j); //printf("%d %d %d\n",i,j,flag); if(flag) { x++; if(max1<ans) max1=ans; } } } } if(x==0) printf("Maze #%d:\nThere are no cycles.\n\n",num); else printf("Maze #%d:\n%d Cycles; the longest has length %d.\n\n",num,x,max1/3); } return 0; }