POJ-2488 A Knight's Journey

来源:互联网 发布:linux查看内存型号 编辑:程序博客网 时间:2024/05/20 01:35
#include <iostream>  #include <string>  #include <cstring>  #include <cstdio>    using namespace std;    int dir[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};  int t, p, q, cas;  int mp[27][27];    int dfs(int x, int y, int step, string ans)  {      if(step == p * q)      {          cout << ans << endl << endl;          return 1;      }      else      {          for(int i = 0; i < 8; i ++)          {              int nx = x + dir[i][0];              int ny = y + dir[i][1];              char ansx = nx + '1';              char ansy = ny + 'A';              if(nx >= 0 && ny >= 0 && nx < p && ny < q && mp[nx][ny] == 0)              {                  mp[nx][ny] = 1;                  if(dfs(nx, ny, step + 1, ans + ansy + ansx))                      return 1;                  mp[nx][ny] = 0;              }          }          return 0;      }  }    int main(void)  {      cin >> t;      cas = 0;      while(t --)      {          cin >> p >> q;          memset(mp, 0, sizeof(mp));          mp[0][0] = 1;          printf("Scenario #%d:\n", ++cas);         if(dfs(0, 0, 1, "A1") == 0)              cout << "impossible" << endl << endl;      }      return 0;  }  

题意:差不多就是给一个棋盘 用马(即”日“字形走法)走完整个棋盘。第一行输入t,表示测试t组。之后输入p q 表示棋盘大小。字典序输出步骤。

题解:就是深度查找...查到一条路径可以输出。要注意字典序输出。所以步子一开始就按方向规定(顺时针正好可字典序)。

0 0
原创粉丝点击