标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7062 Accepted Submission(s): 2009
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <queue> #include <algorithm> using namespace std; int n,m; int graph[8][8]; bool flag[8][8][4]; bool vis[8][8]; int dir[][2] = {{1,0},{-1,0},{0,1},{0,-1}}; struct Node { int x,y; int step; int g[10][10]; }s,person,t; bool check(int x,int y) { if(x<0||x>=n||y<0||y>=m) return false; return true; } bool bfs2(Node s,Node target){ person = s; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(person.g[i][j]==4){ person.x = i; person.y = j; person.step = 0; } } } queue<Node>q; memset(vis,false,sizeof(vis)); q.push(person); vis[person.x][person.y] = true; while(!q.empty()){ Node now = q.front(); q.pop(); if(now.x==target.x&&now.y==target.y){ return true; } Node next; for(int i=0;i<4;i++){ next.step = now.step+1; next.x = now.x +dir[i][0]; next.y = now.y + dir[i][1]; if(!check(next.x,next.y)||s.g[next.x][next.y]==2||vis[next.x][next.y]||s.g[next.x][next.y]==1) continue; vis[next.x][next.y] = true; q.push(next); } } return false; } int bfs(){ memset(flag,false,sizeof(flag)); queue <Node> q; q.push(s); while(!q.empty()){ Node now = q.front(); q.pop(); if(now.x==t.x&&now.y==t.y) return now.step; Node next,target; for(int i=0;i<4;i++){ next = now; next.x = now.x+dir[i][0]; next.y = now.y+dir[i][1]; next.step = now.step+1; if(!check(next.x,next.y)||flag[next.x][next.y][i]||next.g[next.x][next.y]==1) continue; ///该方向已经走过了 ///人的目标点(人以此点为目标点将箱子从now推向next) target.x = now.x - dir[i][0]; target.y = now.y - dir[i][1]; if(!check(target.x,target.y)) continue; if(bfs2(next,target)){ swap(next.g[now.x][now.y],next.g[next.x][next.y]); swap(next.g[target.x][target.y],next.g[person.x][person.y]); flag[next.x][next.y][i] = true; q.push(next); } } } return -1; } int main() { int tcase; scanf("%d",&tcase); while(tcase--) { scanf("%d%d",&n,&m); for(int i=0; i<n; i++) for(int j=0; j<m; j++){ scanf("%d",&s.g[i][j]); if(s.g[i][j]==2){ s.x = i; s.y = j; s.step = 0; } if(s.g[i][j]==3){ t.x = i; t.y = j; } } int res = bfs(); printf("%d\n",res); } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5585469.html