POJ 3050 Hopscotch(dfs,暴力搜索)


Hopscotch
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2780   Accepted: 1944

Description

The cows play the child's game of hopscotch in a non-traditional way. Instead of a linear set of numbered boxes into which to hop, the cows create a 5x5 rectilinear grid of digits parallel to the x and y axes. 

They then adroitly hop onto any digit in the grid and hop forward, backward, right, or left (never diagonally) to another digit in the grid. They hop again (same rules) to a digit (potentially a digit already visited).

With a total of five intra-grid hops, their hops create a six-digit integer (which might have leading zeroes like 000201). 

Determine the count of the number of distinct integers that can be created in this manner.

Input

* Lines 1..5: The grid, five integers per line

Output

* Line 1: The number of distinct integers that can be constructed

Sample Input

1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1

Sample Output

15

Hint

OUTPUT DETAILS: 
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112, 121211, 121212, 211111, 211121, 212111, and 212121 can be constructed. No other values are possible.


题意:在5*5的格子里,填充着各种个位数,现在可以从任意点出发,上下左右移动,可以重复走过的点,每次只能走6步。问经过的格子中组成的6位数(允许有前导零的存在)有多少种?

题解:题目只用输入一组数据啦。我们可以遍历图中的每一个位置,然后从该位置开始暴力搜索,记录走的步数,步数超过6步就停止,并判断这个6位数之前出没出现过。

代码如下:

#include<cstdio>
#include<cstring>
int map[10][10];
int a[10];
int num[100000];//数组要开大啊,1000RE了 
int k;
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};

void dfs(int x,int y,int z)
{
	int i,cnt;
	if(z==6)
	{
		cnt=a[0]*100000+a[1]*10000+a[2]*1000+a[3]*100+a[4]*10+a[5];
		if(k==0)
			num[k++]=cnt;
		else
		{
			int sign=1;
			for(i=0;i<k;++i)//判断是否出现过相同的数 
			{
				if(cnt==num[i])
				{
					sign=0;
					break;
				}
			}
			if(sign)
				num[k++]=cnt;
		}
		return ;
	}
	for(i=0;i<4;++i)
	{
		int nx=x+dir[i][0];
		int ny=y+dir[i][1];
		if(nx>=0&&nx<5&&ny>=0&&ny<5)
		{
			a[z]=map[nx][ny];
			dfs(nx,ny,z+1);
		}
	}
}

int main()
{
	int i,j;
	for(i=0;i<5;++i)
	{
		for(j=0;j<5;++j)
			scanf("%d",&map[i][j]);
	}
	k=0;
	for(i=0;i<5;++i)
	{
		for(j=0;j<5;++j)
		{
			a[0]=map[i][j];//把起始位置记录入数组 
			dfs(i,j,1);
		}
	}
	printf("%d\n",k);
	return 0;
} 


你可能感兴趣的:(POJ 3050 Hopscotch(dfs,暴力搜索))