Problem:跳房子
Description
奶牛按不太传统的方式玩起小朋友玩的跳房子游戏,现给出一个5*5的由数字组成的网格。它们在格子中向前前跳,向后跳,向左跳,向右跳,跳到网格中另一个数字后,又这样继续跳(可能跳到某个已跳过的数字)。一共在网格中跳过五次后,它们经过的格子数组成一个六位数(可能是0开始头的,例如000201).现问所有可以被跳出来的不同整数的总数。
Input
输入共五行,每行五个数字.
Output
输出所有可以被跳出来的不同整数的总数。
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
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112,121211, 121212, 211111, 211121, 212111, 212121
can be constructed.
No other values are possible.
这道题是一道不错的题,他给了你数据可以说明可以反复横跳,所以花花就是这么凉的(心里无语),这道题关键在于你的搜索方式与能力,话不多说,代码理解:
#include<bits/stdc++.h>//可爱的万能头
using namespace std;
int cnt;
string ans;
char mp[11][11];//那个网格
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//搜索四个方向
bool in(int x,int y)//判断是否出界
{
return 1<=x&&x<=5&&1<=y&&y<=5;
}
set<string> s;//set类型去重(很重要)
void dfs(int x,int y,int dep,string an)
{
an+=mp[x][y];//开始搜索之路
if(dep==6)//如果到了第六步
{
if(!s.count(an))//如果不一样
{
s.insert(an);//insert不会的可以去别人的博客上学习学习
cnt++;//符合就增加
}
return;
}
for(int i=0;i<4;i++)
{
int nx=x+dir[i][0],ny=y+dir[i][1];
if(in(nx,ny))
{
dfs(nx,ny,dep+1,an);//继续搜索
}
}
return;
}
int main()
{
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
cin>>mp[i][j];//输入网格
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
dfs(i,j,1,"");//搜索(这种写法萌新应该见过)
}
}
cout<<cnt<<endl;//输出总数
return 0;//完美的结束
}
搜索很重要,方向不能忘,记得删重复,AC你我他。
大家都懂:
#include<bits/stdc++.h>
using namespace std;
int cnt;
string ans;
char mp[11][11];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
bool in(int x,int y)
{
return 1<=x&&x<=5&&1<=y&&y<=5;
}
set<string> s;
void dfs(int x,int y,int dep,string an)
{
an+=mp[x][y];
if(dep==6)
{
if(!s.count(an))
{
s.insert(an);
cnt++;
}
return;
}
for(int i=0;i<4;i++)
{
int nx=x+dir[i][0],ny=y+dir[i][1];
if(in(nx,ny))
{
dfs(nx,ny,dep+1,an);
}
}
return;
}
int main()
{
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
cin>>mp[i][j];
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
dfs(i,j,1,"");
}
}
cout<<cnt<<endl;
return 0;
}
喜欢樱花的留下你的评论吧!!!
(不知道你看得见吗)
点一点关注,蟹蟹!!!