another DFS problem POJ3009

来源:互联网 发布:海丝微盘软件 编辑:程序博客网 时间:2024/05/19 15:40

      it's interesting to let the stone fly and fly

#include <stdio.h>  #include <string.h>  const int dh[4]={-1, 0, 1, 0};  const int dw[4]={0, -1, 0, 1};  char map[24][24];  int w, h, _x, _y;  int ans;  void dfs(int x, int y, int times)  {      if (times >= 10)          return;      if (times > ans)          return;      int xt, yt;      for (int i = 0; i < 4; i++){          xt = x;          yt = y;          while ( (0<=xt&&xt<h) && (0<=yt&&yt<w) // 向某个方向一直飞啊飞~                && (map[xt][yt] == 0 or map[xt][yt] == 2)){//vacant square or start              xt += dh[i];              yt += dw[i];          }          if (0<=xt&&xt<h && 0<=yt&&yt<w && map[xt][yt] == 3){ // 飞过(到)目标了                       if (times+1 < ans){                  ans = times+1;              }          }          else if (!(xt-dh[i]==x && yt-dw[i]==y) // 必须有空地才能飞啊,待在原地不算啊                   && 0<=xt&&xt<h && 0<=yt&&yt<w && map[xt][yt] == 1){ // blocks                        map[xt][yt] = 0;                        dfs(xt-dh[i], yt-dw[i], times+1);                        map[xt][yt] = 1;          }      }  }  int main()  {      while ( 2 == scanf("%d %d", &w, &h) && w && h){          for (int i = 0; i < h; i++){              for (int j = 0; j < w; j++){                  scanf("%d", &map[i][j]);                                if (map[i][j] == 2){                      _x = i;                      _y = j;                  }              }          }          ans = 999;          dfs(_x, _y, 0);          printf("%dn", (ans==999)?(-1):(ans));      }      return 0;  }


原创粉丝点击