![](http://hi.csdn.net/attachment/201107/30/0_1312045975wCTo.gif)
字典序 x 1-7 y A-B
{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}
深度搜索如果避免存在回边的情况,即马要 不重复的 走过所有格。
点击(此处)折叠或打开
- #include <iostream>
- #include <list>
- #include <cstring>
-
- using namespace std;
-
-
- #define MAX_V (26+1)
- char board[MAX_V][MAX_V];
- int p,q,n;
-
- struct move
- {
- int i;
- int j;
- //}MOVE[8]={{1,-2},{-1,-2},{2,-1},{-2,-1},{2,1},{-2,1},{1,2},{-1,2}};
- //}MOVE[8]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2},};
- //}MOVE[8]={{2,-1},{1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};
- //}MOVE[8]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
- }MOVE[8]={ {-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
- //}MOVE[8]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
-
- struct qv
- {
- int i;
- int j;
- };
-
-
- list<struct qv> dfsList;
-
- int is_valid(int i,int j)
- {
- if(i < 1 || i> p)
- return 0;
- if(j< 1 || j> q)
- return 0;
-
- return 1;
- }
- int dfsVisit(int i,int j)
- {
-
- board[i][j]=1;
- struct qv _qv = {i,j};
- dfsList.push_back(_qv);
-
- if(dfsList.size() == p*q)
- return 1;
-
- for(int m=0;m<8;m++)
- {
- int mi=MOVE[m].i +i;
- int mj = MOVE[m].j +j;
-
- if(!is_valid(mi,mj))
- continue;
- if(board[mi][mj] == 0)
- {
- if(dfsVisit(mi,mj))
- {
- return 1;
- }
- }
- }
-
- board[i][j]=0;
- dfsList.pop_back();
- return 0;
- }
-
- int dfs()
- {
- for(int i=1;i<=p;i++)
- {
- for(int j=1;j<=q;j++)
- {
- memset(board,0,sizeof(board));
- dfsList.erase(dfsList.begin(),dfsList.end());
- //try start with i,j
- dfsVisit(i,j);
- //cout<<"after dfs i:"<<i<<"j:"<<j<<"size:"<<dfsList.size()<<endl;
-
- if(dfsList.size() == p*q)
- {
- return 1;
- }
- }
- }
-
- return 0;
- }
-
- int index_v=1;
- int main()
- {
- cin >> n;
- for(int k=1;k<=n;k++)
- {
- cin >>p>>q;
- //cout<<"p:"<<p<<"q:"<<q<<endl;
-
- cout<<"Scenario #"<<index_v<<":"<<endl;
- if(dfs())
- {
- for(list<struct qv>::iterator lIter = dfsList.begin();
- lIter != dfsList.end();
- ++lIter)
- {
- struct qv _qv = (*lIter);
- cout<<(char)(_qv.j+'A'-1)<<_qv.i;
- }
- cout<<endl;
- }
- else
- {
- cout<<"impossible"<<endl;
- }
- cout<<endl;
-
- index_v++;
- }
- }
相关热门文章
给主人留下些什么吧!~~
评论热议