By filling a rectangle with slashes (/) and backslashes (
), you can generate nice little mazes. Here is an example:
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.
Input
The input contains several maze descriptions. Each description begins with one line containing two integers w 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.
Output
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.
Sample Input
6 4 \//\\/ \///\/ //\\/\ \/\/// 3 3 /// \// \\\ 0 0
Sample Output
Maze #1: 2 Cycles; the longest has length 16. Maze #2: There are no cycles.
题意:
我们将图像进行扩大,变成原来的三倍;
先画一个九宫格,放入斜干,有斜干的方格记为1,没有斜干的方格记为0;
0表示可以走,则1表示不可以走;
那么我们就就可以将图像变为通常的dfs进行;
#include<stdio.h>
#include<string.h>
int num=0,f,sum,max,pos,h,w;
int move[4][2]={1,0,-1,0,0,-1,0,1};
int map[400][400];
void dfs(int x,int y)
{
int X,Y,i;
for (i=0;i<4;i++)
{
X=x+move[i][0];
Y=y+move[i][1];
if ((X>=0)&&(X<h*3)&&(Y>=0)&&(Y<w*3))
{
if (map[X][Y]==0)
{
++pos;
map[X][Y]=1;
dfs(X,Y);
}
}
else
f=0;
}
}
int main()
{
int i,j;
char s[200];
while (scanf("%d%d",&w,&h) != EOF)
{
if(w==0 && h ==0)
break;
getchar();
++num; sum=0; max=0;
memset(map,0,sizeof(map));
for (i=0;i<h;i++)
{
gets(s);
for (j=0;j<w;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+2][3*j]=1;
map[3*i+1][3*j+1]=1;
map[3*i][3*j+2]=1;
}
}
for (i=0;i<3*h;i++)
for (j=0;j<3*w;j++)
{
if (map[i][j]==0)
{
pos=1; f=1;
map[i][j]=1;
dfs(i,j);
if (f)
{
++sum;
if (pos>max)
max=pos;
}
}
}
if (sum==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,sum,max/3);
}
return 0;
}
本文介绍了一种通过深度优先搜索算法来解决迷宫周期计数问题的方法。通过对迷宫进行特殊转换并应用DFS,可以有效地找出迷宫中的所有周期及其最长路径长度。
832

被折叠的 条评论
为什么被折叠?



