POJ3050 Hopscotch - 穷竭搜索

Hopscotch

Time Limit: 1000MS     Memory Limit: 65536K
Total Submissions: 6735     Accepted: 4335

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的由单个数字组成的矩阵,任选一个位置作为起点,然后跳跃5次,每次跳跃可以向上下左右中的一个方向移动(不能超过边缘)。经过5次跳跃后,共访问了6个数字(可能会有重复),把这6个数字依次拼接成一个6位数(可能会有前导零),问可能会出现多少种6位数。

 
 

分析:

由于只跳跃5次,因此选定一个出发点后,每次跳跃只有上下左右 4 4 4 种选择,因此只有不超过 4 5 4^5 45 种不同的路径,而出发点共有 5 × 5 = 25 5×5=25 5×5=25 种选择,因此总复杂度为 O ( 5 2 × 4 5 ) O(5^2×4^5) O(52×45) ,完全没有问题。

重点是 d f s dfs dfs 函数的写法和去除重复的办法,我这里传递4个参数 s , b a s e , x , y s,base,x,y s,base,x,y ,分别代表:当前已形成的数,当前跳跃在十进制数中的位权, x x x坐标, y y y坐标。去重的化,我直接使用了 S T L STL STL 中的 s e t set set ,当然由于形成的数最大不会超过 1 0 6 10^6 106 ,因此用一个大小为 1 0 6 10^6 106 b o o l bool bool 型数组来记录每个数字有没有出现过,最后再遍历一遍也可以。

 
 
下面贴代码:

#include <cstdio>
#include <set>
using namespace std;

const int dx[4] = { -1,0,0,1 };
const int dy[4] = { 0,-1,1,0 };
const int MAX_N = 5;

int A[MAX_N][MAX_N];
void dfs(int s, int base, int x, int y);
set<int> st;

int main()
{
	for (int i = 0; i < MAX_N; ++i)
	{
		for (int j = 0; j < MAX_N; ++j)
		{
			scanf("%d", A[i] + j);
		}
	}
	for (int i = 0; i < MAX_N; ++i)
	{
		for (int j = 0; j < MAX_N; ++j)
		{
			dfs(0, 100000, i, j);
		}
	}
	printf("%d\n", st.size());
	return 0;
}

void dfs(int s, int base, int x, int y)
{
	if (base)
	{
		s += base * A[x][y];
		for (int i = 0; i < 4; ++i)
		{
			int px = x + dx[i];
			int py = y + dy[i];
			if (0 <= px && px < MAX_N && 0 <= py && py < MAX_N)
			{
				dfs(s, base / 10, px, py);
			}
		}
	}
	else
	{
		st.insert(s);
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值