https://vjudge.net/problem/UVA-705
题解:这个题目我们可以把斜线变成一个2成2的方格,然后我们往8个方向搜索,先搜直的四个方向,在搜斜的,斜的方向可走当且仅当这俩个点所在的方格的斜线都平行与这俩点连成的直线,看看我盗来的这个图就明白了。

扩大2陪
~~~c
#include<iostream>
#include<algorithm>
using namespace std;
int s[200][200];
char c[200][200];
int _max=0;
int cnt=0;
int n,m,ri,cj;
int dx[10]={-1,0,1,0,-1,1,-1,1};
int dy[10]={0,1,0,-1,-1,-1,1,1};
int judge(int x,int y,int fx,int fy,int k)
{
int i1=(x+1)/2;int j1=(y+1)/2;
int i2=(fx+1)/2;int j2=(fy+1)/2;
if(k==4||k==7)
return c[i1][j1]=='\\'&&c[i2][j2]=='\\';
else
return c[i1][j1]=='/'&&c[i2][j2]=='/';
}
void dfs(int x,int y,int len)
{
if(x==ri&&y==cj&&len>=4)
{
cnt++;
_max=max(_max,len);
return ;
}
if(s[x][y])
return ;
s[x][y]=2;
for(int i=0;i<8;i++)
{
int fx=x+dx[i];
int fy=y+dy[i];
if((fx>=1&&fx<=2*n&&fy>=1&&fy<=2*m)&&(i<4||judge(x,y,fx,fy,i)))
{
dfs(fx,fy,len+1);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int l=0;
while(cin>>m>>n)
{
if(n==0&&m==0)
break;
l++;cnt=0;_max=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>c[i][j];
if(c[i][j]=='/')
{
s[i*2][2*j]=0;
s[i*2][2*j-1]=1;
s[i*2-1][2*j-1]=0;
s[i*2-1][2*j]=1;
}
else if(c[i][j]=='\\')
{
s[i*2][2*j]=1;
s[i*2][2*j-1]=0;
s[i*2-1][2*j-1]=1;
s[i*2-1][2*j]=0;
}
}
}
for(int i=1;i<=2*n;i++)
{
for(int j=1;j<=2*m;j++)
{
if(s[i][j]==0)
{
ri=i;
cj=j;
dfs(i,j,0);
}
}
}
printf("Maze #%d:\n",l);
if(cnt)
{
printf("%d Cycles; the longest has length %d.\n",cnt,_max);
}
else
{
printf("There are no cycles.\n");
}
printf("\n");
}
return 0;
}
扩展3陪
~~~c++
#include<iostream>
#include<algorithm>
using namespace std;
int s[300][300];
char c[300][300];
int _max=0;
int cnt=0;
int n,m,ri,cj;
int f,pos;
int dx[10]={-1,0,1,0,-1,1,-1,1};
int dy[10]={0,1,0,-1,-1,-1,1,1};
void dfs(int x,int y,int len)
{
s[x][y]=1;
for(int i=0;i<4;i++)
{
int fx=x+dx[i];
int fy=y+dy[i];
if(fx>=1&&fx<=3*n&&fy>=1&&fy<=3*m)
{
if(s[fx][fy]==0)
{
pos++;
dfs(fx,fy,len+1);
}
}
else
f=0;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int l=0;
while(cin>>m>>n)
{
if(n==0&&m==0)
break;
l++;cnt=0;_max=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>c[i][j];
if(c[i][j]=='/')
{
s[i*3-2][3*j-2]=0;
s[i*3-2][3*j-1]=0;
s[i*3-2][3*j]=1;
s[i*3-1][3*j-2]=0;
s[i*3-1][3*j-1]=1;
s[i*3-1][3*j]=0;
s[i*3][3*j-2]=1;
s[i*3][3*j-1]=0;
s[i*3][3*j]=0;
}
else if(c[i][j]=='\\')
{
s[i*3-2][3*j-2]=1;
s[i*3-2][3*j-1]=0;
s[i*3-2][3*j]=0;
s[i*3-1][3*j-2]=0;
s[i*3-1][3*j-1]=1;
s[i*3-1][3*j]=0;
s[i*3][3*j-2]=0;
s[i*3][3*j-1]=0;
s[i*3][3*j]=1;
}
}
}
for(int i=1;i<=3*n;i++)
{
for(int j=1;j<=3*m;j++)
{
if(s[i][j]==0)
{
f=1;pos=0;
dfs(i,j,0);
if(f)
{
cnt++;
_max=max(pos+1,_max);
}
}
}
}
printf("Maze #%d:\n",l);
if(cnt)
{
printf("%d Cycles; the longest has length %d.\n",cnt,_max/3);
}
else
{
printf("There are no cycles.\n");
}
printf("\n");
}
return 0;
}
本文深入解析了UVA-705迷宫问题,通过将斜线转化为2x2方格,利用深度优先搜索算法,对八个方向进行搜索,以判断是否存在回路,并计算最长回路长度。提供了详细的C++代码实现。
837

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



