bfs类的题,加了内存处理之后自己运行一直不对,但不处理泄漏的内存,能出正确结果,注释掉之后一次Ac。内存泄漏问题,等着再看看。。
#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; }