题目:http://poj.org/problem?id=3984
很经典用BFS解决的了。
#include<iostream>
#include<string.h>
#include<queue>
#define INF 1e18
#define inf 1e9
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const int n = 5;
int dx[]={1,-1,0,0};
int dy[]={0,0,-1,1};
bool mp[6][6];
struct node{
int x,y,step,nx,ny;
bool operator < (const node &n1)const{
return step > n1.step;
}
void count(){
this->step = (n-x)+(n-y);
}
};
struct node1{
int nx,ny;
void init(node n){
this->nx = n.nx;
this->ny = n.ny;
}
};
priority_queue<node> q;
node1 m[6][6];
bool outside(node n1){
if(mp[n1.x][n1.y]) return false;
if(n1.x > n || n1.x < 1) return false;
if(n1.y > n || n1.y < 1) return false;
return true;
}
void bfs(){
while(!q.empty()) q.pop();
node now,next;
now.x = 1,now.y = 1;
now.count();
q.push(now);
while(!q.empty()){
now = q.top();
q.pop();
// cout<<now.x<<' '<<now.y<<endl;
for(int i = 0 ; i < 4 ; i++){
next.x = now.x+dx[i];
next.y = now.y+dy[i];
next.nx = now.x,next.ny = now.y;
if(!outside(next)) continue;
m[next.x][next.y].init(next);
mp[next.x][next.y] = true;
next.count();
q.push(next);
if(next.x == n&&next.y ==n) return;
}
}
}
void print(int x,int y){
if(x != 1||y != 1)
print(m[x][y].nx,m[x][y].ny);
cout<<"("<<x-1<<", "<<y-1<<")"<<endl;
}
int main(){
memset(m,0,sizeof(m));
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= n ; j++)
cin>>mp[i][j];
bfs();
print(5,5);
return 0;
}