将整个图像放大两倍后,其中间空格数恰好为所求空格数,注意整个图像外圈需要围上一圈"#"号以作边界;然后DFS 8个方向进行深度优先搜索,这里需注意,有对角线的四个方向需要特殊条件(判断是否相通)才可遍历,否则不遍历 ~
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define max 100+5
int num,max_l,t,fflag,vis[150+4][150+4];
char a[150+4][150+4];
void dfs(int x, int y)
{
if(a[x][y]=='/' || a[x][y]=='\\' || vis[x][y])
return ;
if(a[x][y] == '#') //如果遇到‘#’,则fflag=1,num 与 max_l 不进行 计数 和 判断赋值
{
fflag = 1;
return ;
}
vis[x][y] = 1;
t++;
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);
if(a[x+1][y]=='\\' && a[x][y+1]=='\\') //特殊判断,只有此时通路时才可遍历
dfs(x+1,y+1);
if(a[x][y-1]=='/' && a[x+1][y]=='/')
dfs(x+1,y-1);
if(a[x-1][y]=='/' && a[x][y+1]=='/')
dfs(x-1,y+1);
if(a[x-1][y]=='\\' && a[x][y-1]=='\\')
dfs(x-1,y-1);
}
int main()
{
#ifdef state
freopen("sample.txt","r",stdin);
#endif
int w,h,i,j,cct = 0;
char c;
while(scanf("%d%d",&w,&h), (w || h))
{
printf("Maze #%d:\n",++cct);
num = 0, max_l = 0;
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
for(i = 0; i <= 2*h+1; i++) // 赋予边界
{
a[i][0] = '#';
a[i][2*w+1] = '#';
}
for(i = 0; i <= 2*w+1; i++)
{
a[0][i] = '#';
a[2*h+1][i] = '#';
}
for(i = 1; i <= h; i++)
{
getchar();
for(j = 1; j <= w; j++)
{
scanf("%c",&c);
if(c == '/')
{
a[2*(i-1)+1][2*(j-1)+1] = '*'; // 为了检查方便,可将空格换成 '*' 号。
a[2*(i-1)+1][2*(j-1)+2] = '/';
a[2*(i-1)+2][2*(j-1)+1] = '/';
a[2*(i-1)+2][2*(j-1)+2] = '*';
}
else
{
a[2*(i-1)+1][2*(j-1)+1] = '\\';
a[2*(i-1)+1][2*(j-1)+2] = '*';
a[2*(i-1)+2][2*(j-1)+1] = '*';
a[2*(i-1)+2][2*(j-1)+2] = '\\';
}
}
}
for(i = 1; i <= 2*h; i++)
for(j = 1; j <= 2*w; j++)
if(a[i][j]=='*' && !vis[i][j])
{
fflag = t = 0;
dfs(i,j);
if(!fflag) // 只要不遇上 '#' 号,所计封闭图形就要进行判断计数
{
if(t > max_l)
max_l = t;
num++;
}
}
if(!num)
printf("There are no cycles.\n\n");
else
printf("%d Cycles; the longest has length %d.\n\n",num,max_l);
}
return 0;
}