Slash Maze
Slash Maze |
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 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.
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.
Miguel A. Revilla
2000-02-09
这道题题意真是新颖,看到题目完全无从下手,想了很久都找不到思路,后来看了大神的想法,把斜杠放大成3*3格子,斜杠经过的是1没经过的是0,之后就比较好处理了,思路豁然开朗,但是之后判断是不是存在封闭图形的时候,有个注意的地方—在搜索一个点四周的时候,如果越界了那肯定不构成封闭图形。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int grid[300][300];
int n,m,w,h,s,len,maxlen,f;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
void dfs(int x,int y)
{
int nx,ny;
for(int i=0;i<4;i++)
{
nx=x+dx[i];
ny=y+dy[i];
if(nx>=0&&nx<h&&ny>=0&&ny<w)
{
if(grid[nx][ny]==0)
{
len++;
grid[nx][ny]=1;
dfs(nx,ny);
}
}
else
{
f=0;
}
}
}
int main()
{
int num=0;
while(cin>>n>>m&&n!=0&&m!=0)
{
memset(grid,0,sizeof(grid));
int i,j,k;
w=n*3,h=3*m;
string str;
for(i=0;i<m;i++)
{
cin>>str;
for(j=0;j<n;j++)
{
if(str[j]=='/')
{
grid[3*i+2][j*3]=1;
grid[3*i+1][3*j+1]=1;
grid[3*i][j*3+2]=1;
}
else if(str[j]=='\\')
{
grid[3*i][j*3]=1;
grid[3*i+1][3*j+1]=1;
grid[3*i+2][3*j+2]=1;
}
}
}
s=0,maxlen=0;
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
{
if(grid[i][j]==0)
{
grid[i][j]=1;
len=1;
f=1;
dfs(i,j);
if(f!=0)
{
s++;
if(len>maxlen) maxlen=len;
}
}
}
}
cout<<"Maze #"<<++num<<":"<<endl;
if(s!=0)
cout<<s<<" Cycles; the longest has length "<<maxlen/3<<"."<<endl;
else
cout<<"There are no cycles."<<endl;
cout<<endl;
}
return 0;
}