UVa 439 - Knight Moves

bfs类的题,加了内存处理之后自己运行一直不对,但不处理泄漏的内存,能出正确结果,注释掉之后一次Ac。内存泄漏问题,等着再看看。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<queue>
#include<vector>
using namespace std;
struct Point{
int a,b;
Point(int a=0,int b=0):a(a),b(b){}
Point operator + (const Point A) const {
Point temp;
temp=Point(a+A.a,b+A.b);
return temp;
}
bool operator ==(const Point A) const{
return a==A.a&&b==A.b;
}
};
struct Node{
Point a;
Node *p[8];
Node(Point a=Point()):a(a){}
};
int k[8][2]={{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1}};
bool arrived[8][8];
Point jump[8],sta,ed;
map<char,int>x;
queue<Node*>deep;
vector<queue<Node*> >tree;
bool should_jump(Point a,Point b){
Point temp;
temp=a+b;
if(temp.a>=0&&temp.a<8&&temp.b>=0&&temp.b<8&&!arrived[temp.a][temp.b]) return true;
return false;
}
Node* newnode(){
Node *temp;
temp=new Node();
for(int i=0;i<8;i++)
temp->p[i]=NULL;
return temp;
}
Point read_point(string a){
Point temp;
temp.a=x[a[0]];
temp.b=a[1]-'1';
return temp;
}
void arrive(Point a){
arrived[a.a][a.b]=true;
return;
}
void build(Node* a,int k){
for(int i=0;i<8;i++)
if(should_jump(a->a,jump[i])){
a->p[i]=new Node();
a->p[i]->a=a->a+jump[i];
arrive(a->p[i]->a);
tree[k].push(a->p[i]);
}
}
void remove_tree(Node* a){
if(a==NULL) return;
for(int i=0;i<8;i++)
remove_tree(a->p[i]);
delete a;
}
int main(){
for(int i=0;i<8;i++){
jump[i].a=k[i][0];
jump[i].b=k[i][1];
x['a'+i]=i;
}
string s0,s;
while(cin>>s0>>s){
int move;
Node* root;
memset(arrived,0,sizeof(arrived));
sta=read_point(s0);
arrive(sta);
ed=read_point(s);
if(sta==ed){
move=0;
goto END;
}
root=newnode();
root->a=sta;
tree.push_back(deep);
tree.push_back(deep);
tree[0].push(root);
move=1;
while(1){
if(arrived[ed.a][ed.b]) break;
if(tree[0].empty()){
tree.erase(tree.begin());
tree.push_back(deep);
move++;
}
build(tree[0].front(),1);
tree[0].pop();
}
END:
cout<<"To get from "<<s0<<" to "<<s<<" takes "<<move<<" knight moves."<<endl;
//remove_tree(root);
tree.clear();
}
return 0;
}

本文迁移自我的 CSDN博客 ,格式可能有所偏差。