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
这道题输入规模不大,可以直接穷举。下面代码中的查不同数可以直接用STL中的map容器,每找到一个数就insert,且不会重复插入。
#include <iostream>
#include<cmath>
#include<cstring>
using namespace std;
int grid[5][5];
int a[1000000];
int tx,ty,dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
void solve();
void dfs(int i,int sum,int x,int y);
int main()
{
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>grid[i][j];
}
}
solve();
return 0;
}
void solve(){
int i,j,k,t;
memset(a,0,sizeof(a));
for(i=0;i<5;i++){
for(j=0;j<5;j++){
dfs(1,grid[i][j],i,j);
}
}
int ans=0;
for(i=0;i<1000000;i++){
if(a[i]) ++ans;
}
cout<<ans<<endl;
}
void dfs(int i,int sum,int x,int y){
if(i>=6) {
//debug
//cout<<sum<<endl;
a[sum]=1;return;
}
for(int j=0;j<4;j++){
tx=x+dx[j];ty=y+dy[j];
if(tx>=0&&tx<5&&ty>=0&&ty<5){
//既然要保留现场,那在函数外切记不可修改原始形参值
//sum+=grid[tx][ty]*(int)pow(10.0,i);
int temp=sum+grid[tx][ty]*(int)pow(10.0,i);
dfs(i+1,temp,tx,ty);
}
}
}