Hopscotch
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3460 | Accepted: 2380 |
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.
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.
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次,每走一次记录下所走格子的数字,经过以上步奏,把总共6个数字连起来,形成一串数字。求总共可以形成多少种不同的数字串
思路
暴力搜索,数据略水,这里我用了STL的set容器来去重,简单的说就是把所有的可能都放到set容器里面,最后只要输出容器内有多少个数字就好了
详细见代码
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
int map[5][5];
int gx[] = {0,0,1,-1};//遍历4个方向
int gy[] = {1,-1,0,0};
set<int> s;
int temp;//每次的结果暂时保存
bool Write()//写入函数
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(cin>>map[i][j])
continue;
else
return false;
}
}
return true;
}
void dfs(int x,int y,int depth)//depth表示深度,当到第6个以后就把temp放入容器中
{
if(depth == 6)
{
s.insert(temp);
return ;
}
for(int i=0;i<4;i++)
{
int tx = x + gx[i];
int ty = y + gy[i];
if(tx<0 || tx>=5 || ty<0 || ty>=5)//判断是否出界
continue;
temp = temp*10 + map[tx][ty];//将数字扩大10倍,把地图上对应点的数字加到末尾
dfs(tx,ty,depth+1);
temp = temp/10; //直接删除末尾数字
}
}
int main()
{
while(Write())
{
temp = 0;//注意初始化
while(!s.empty())//注意每次提前清空容器
s.clear();
for(int i=0;i<5;i++)//遍历每一个点
{
for(int j=0;j<5;j++)
{
dfs(i,j,0);
}
}
cout<<s.size()<<endl;
}
return 0;
}
奈何我冒泡的算法如何打动你超时的心!!!