Description
Input
Output
Sample Input
3 1 1 2 3 4 3
Sample Output
Scenario #1: A1 Scenario #2: impossible Scenario #3: A1B3C1A2B4C2A3B1C3A4B2C4
这题的搜索不难,难在字典序。而看了看题解后发现是有规律的。只要每次dfs要从每列这样遍历,而且方向数组要从左到右,再从上到下的次序就能保证是最小的字典序了。
AC代码:
#include
#include
#include
#include
#include
#include
using namespace std;
#define CRL(a) memset(a,0,sizeof(a))
vector< pair > k;
pair v;
int n,m,flag,cnt;
int fx[][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1}
,{-2,1},{2,1},{-1,2},{1,2}};
int map[55][55];
bool jugde(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=m&&!map[x][y]){
return true;
}
return false;
}
void dfs(int x,int y,int c)
{
int tx,ty;
if(c==n*m){flag=0;}
if(!flag)return;
for(int i=0;i<8;++i){
v.first=x, tx = fx[i][0] + x;v.first=tx;
v.second=y, ty = fx[i][1] + y;v.second=ty;
if(jugde(tx,ty)){
k.push_back(v);map[tx][ty]=1;
dfs(tx,ty,c+1);
if(!flag)return;
k.pop_back();
map[tx][ty]=0;
}
}
}
int main()
{
/*freopen("input.txt","r",stdin);*/
int N,i,j,c=0;
scanf("%d",&N);
while(N--)
{
flag = 1;cnt=0;
scanf("%d%d",&n,&m);
printf("Scenario #%d:\n",++c);
for(i=1;i<=m&&flag;++i){
for(j=1;j<=n&&flag;++j){
map[j][i] = 1;//这里只是换了m,n位置而未换i,j所以wa了
v.first = j,v.second = i;
k.push_back(v);
dfs(j,i,1);
CRL(map);
if(flag)
k.clear();
}
}
if(!flag){
for(i=0;i