您的位置:首页 > 其它

uva 705

2013-08-03 10:58 120 查看
题意: 在斜迷宫内,并且在范围内,找环,以及个数,并求出最大值。。

思路: 这道题如果放大3倍后,就会变得比较简单了 ,而这道题有一个简单的地方就是只要用dfs便能找到一个环,而条件就是在范围内

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int 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)
{
	for (int i = 0 ; i < 4 ; i++)
	{
		int nx = x + move[i][0];
		int ny = y + move[i][1];
		if ( nx >= 0 && nx < 3*h && ny >= 0 && ny < 3*w )
        {
            if (map[nx][ny] == 0)
			{
				++pos;
				map[nx][ny] = 1;
				dfs(nx,ny);
			}
        }
        else f = 0;   // 其实只要能在范围内,这道题用dfs一定能形成一个环
	}
}

int main()
{
	int i,j,cas=0;
	char s[200];
	while (scanf("%d%d",&w,&h) != EOF && w+h)
	{
		getchar();
		sum=0,Max=0;
		cas++;
		for ( i = 0 ; i < h*3 ; i++)
			for ( j = 0 ; j < w*3 ; j++)
				map[i][j] = 0 ;

		for ( i = 0 ; i < h ; i++)
		{
			gets(s);
			for ( j = 0 ; j < w ; j++)
				if ( s[j] == '\\')
					map[3*i][3*j]=map[3*i+1][3*j+1]=map[3*i+2][3*j+2]=1;
				else map[3*i+2][3*j]=map[3*i+1][3*j+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",cas);  
	    else 
		    printf("Maze #%d:\n%d Cycles; the longest has length %d.\n\n",cas,sum,Max/3);
    }
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: