My level is limited and I am only for learning. If you find any mistakes, thank you for pointing out
2016 —— T7
topic:
Idea:
Special judgment is possible, but it is easy to miss the situation. Consider the simplest method here and will not miss it.
1. Search in eight directions first , and then judge the connectivity of the paths found in the eight directions (the DFS can be reached through up, down, left, and right )
Why search eight directions?
Because dfs needs to be backtracked, so 5 and 10 are positions that can be reached by one step for 6, and they cannot exist at the same time. This violates the above example and misses the situation.
2. Judgment , sort the paths , and save the ID in the form of a string, such as concatenating 1 2 3 4 5 into a string "12345"
For the searched path, because 1 2 3 4 5, and 5 3 2 1 4 are actually a path, the search result must be judged seriously.
Tips: Since the implementation of struct in C++ is class, there is no typedef or adding struct to use structure. Literary lovers watch carefully, the code style is weird.
#include<bits/stdc++.h>
using namespace std;
int mp[5][5]={
{
0,0,0,0,0},{
0,1,2,3,4},{
0,5,6,7,8},{
0,9,10,11,12}};
int dx[8]={
1,-1,0,0,-1,-1,1,1},dy[8]={
0,0,-1,1,-1,1,-1,1},vis[5][5];
int xx[4]={
0,0,1,-1},yy[4]={
1,-1,0,0},book[5][5];
int cnt;
set<string>se;//judge repetition
struct pos{
int x,y;
};
pos path[20];
string tostring(int n)
{
stringstream ss;
ss<<n;
return ss.str();
}
void dfs_check(pos p)
{
book[p.x][p.y]=0;
for(int i=0;i<4;i++){
pos t;
t.x=p.x+xx[i],t.y=p.y+yy[i];
if(book[t.x][t.y]==0)continue;
cnt++;
dfs_check(t);
}
return ;
}
int check()
{
cnt=1;memset(book,0,sizeof(book));
for(int i=1;i<=5;i++)book[path[i].x][path[i].y]=1;
dfs_check(path[1]);
return cnt==5?1:0;
}
void dfs(pos p,int step)//eight directions dfs
{
if(step==5){
if(check()){
string id="";//生成唯一路径id利用set判重
int temp[20];//将path路径复制一份,避免排序后对原来回溯干扰
for(int i=1;i<=5;i++)temp[i]=mp[path[i].x][path[i].y];
sort(temp+1,temp+6);
for(int i=1;i<=5;i++)id+=tostring(temp[i]);
se.insert(id);
}
return ;
}
for(int i=0;i<8;i++){
pos t;
t.x=p.x+dx[i],t.y=p.y+dy[i];
if(t.x<1||t.x>3||t.y<1||t.y>4||vis[t.x][t.y]==1)continue;
vis[t.x][t.y]=1;
path[step+1]=t;
dfs(t,step+1);
vis[t.x][t.y]=0;//recall
}
}
int main()
{
for(int i=1;i<=3;i++){
for(int j=1;j<=4;j++){
memset(vis,0,sizeof(vis));
pos s;s.x=i,s.y=j;//start
path[1]=s;vis[i][j]=1;
dfs(s,1);
}
}
return cout<<se.size()<<endl,0;
}