poj 3050 Hopscotch 【DFS 暴力】

来源:互联网 发布:网络营销软件哪个好 编辑:程序博客网 时间:2024/06/06 08:27

Hopscotch

Time Limit: 1000MS

 Memory Limit: 65536KTotal Submissions: 2455 Accepted: 1751

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 11 1 1 1 11 1 1 1 11 1 1 2 11 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次跳跃(跳跃:上下左右,允许经过一个点多次但不能越界)可以依次组成一个6位数(包括起点的那个数),问你这个矩阵能够得到多少个不同的数。

思路:暴力 DFS 5*5矩阵够用了。 我用一个布尔数组vis来标记某个数是否出现过,出现为true,反之为false。 这样就是简单DFS了。详细看代码:

注意:000200 和 002000 属于一种,还有输出结果时没有空格。

没想到跑了0ms:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int map[5][5];bool vis[999999+1];//最大数999999 所以数组够用了 int move[4][2] = {0,1, 0,-1, 1,0, -1,0};int ans;//记录总数目 bool judge(int x, int y)//判断是否越界 {return x >= 0 && x < 5 && y >= 0 && y < 5;}void DFS(int x, int y, int use, int num)//(i, j)表示坐标,use记录跳跃次数,num表示当前组成的数 {if(use == 6)//包括起点 走过6个位置 { if(!vis[num])//组成的数以前没有出现过  { ans++; vis[num] = true; }  return ;}for(int k = 0; k < 4; k++){int next_x = x + move[k][0];int next_y = y + move[k][1];if(judge(next_x, next_y))DFS(next_x, next_y, use + 1, num * 10 + map[next_x][next_y]);//跳跃次数加一 更新组成的数 }}int main(){for(int i = 0; i < 5; i++)//输入矩阵 {for(int j = 0; j < 5; j++)scanf("%d", &map[i][j]);} memset(vis, false, sizeof(vis));//初始化 ans = 0;//统计结果 for(int i = 0; i < 5; i++)//输出矩阵 {for(int j = 0; j < 5; j++)DFS(i, j, 1, map[i][j]);}printf("%d", ans);//注意没有空格 return 0;} 





0 0
原创粉丝点击