uva 10047 The Monocycle

来源:互联网 发布:oracle创建表的sql语句 编辑:程序博客网 时间:2024/06/14 19:33

题意:一个人在n*m的网格上骑着独轮车,网格中存在着一些障碍物,骑车人从某个格子出发,希望用最短的时间到达终点,他要么气到下一个格子,要么左转,要么右转。每个动作需要一秒。初始时他朝北,并且绿色在底面,要求到达终点时,也必须是绿色贴着地面。


分析:从起点出发进行bfs,把坐标x,y,方向d,颜色c,看成一个状态,存入set中判重,bfs找到的第一个解即是最优解。刚开始小于号重载写错了,结果重复状态无法判断。。。


以下附上代码:

#include <algorithm>#include <iostream>#include <sstream>#include <fstream>#include <cstring>#include <cstdio>#include <vector>#include <cctype>#include <cmath>#include <stack>#include <queue>#include <list>#include <map>#include <set>using namespace std;typedef long long ll;typedef unsigned long long ull;const int maxn = 30;struct Node{  int x,y;  int d;//朝向 0N 1E 2S 3W    int c;//底色 0GREEN 1BLACK 2RED 3BLUE 4 WHITE  int time;    Node(){}  Node(int x_, int y_, int d_, int c_, int time_) :    x(x_), y(y_), d(d_), c(c_), time(time_) {}      bool operator < (const Node &b) const{    if(x != b.x) return x < b.x;    if(y != b.y) return y < b.y;    if(d != b.d) return d < b.d;    return c < b.c;  }    Node update(int op){        Node newNode = *this;        if(op == 0){//前进           switch(d){        case 0:--newNode.x;break;//N        case 1:++newNode.y;break;//E        case 2:++newNode.x;break;//S        case 3:--newNode.y;break;//W        default:break;      }      ++newNode.c;      if(newNode.c > 4) newNode.c = 0;          }    else if(op == 1){//左转       --newNode.d;      if(newNode.d < 0) newNode.d = 3;    }    else if(op == 2){//右转       ++newNode.d;      if(newNode.d > 3) newNode.d = 0;          }    ++newNode.time;        return newNode;  }};int n,m;char maze[maxn][maxn];set<Node> Set;queue<Node> q;bool input(){  scanf("%d%d",&n,&m);  if(n == 0 && m == 0)    return false;  memset(maze,'#',sizeof(maze));  for(int i = 1; i <= n; i++){    for(int j = 1; j <= m; j++){      cin >> maze[i][j];    }  }  return true;}int solve(){    //clear  while(!q.empty()) q.pop();  Set.clear();    for(int i = 1; i <= n; i++){    for(int j = 1; j <= m; j++){      if(maze[i][j] == 'S'){        q.push(Node(i,j,0,0,0));        Set.insert(Node(i,j,0,0,0));      }    }  }    Node tNode;  Node newNode;    while(!q.empty()){    tNode = q.front(); q.pop();    //cout << tNode.x << " " << tNode.y << " " << tNode.d << " " << tNode.c << " tNode\n";    //system("pause");        for(int i = 0; i < 3; i++){      newNode = tNode.update(i);      if(maze[newNode.x][newNode.y] == 'T' && newNode.c == 0){        return newNode.time;        }//      cout << newNode.x << " " << newNode.y << "newNode\n";//      system("pause");            if(Set.find(newNode) == Set.end() && maze[newNode.x][newNode.y] != '#'){        q.push(newNode);        Set.insert(newNode);      }    }  }    return -1;}int main(){  int cnt = 0;    while(input()){    if(cnt) puts("");    printf("Case #%d\n",++cnt);    int t = solve();    if(t == -1){      puts("destination not reachable");    }    else{      printf("minimum time = %d sec\n",t);    }      }return 0;}


0 0