B. Bad Queen
Time limit per test: 1.0 seconds
Memory limit: 256 megabytes
There is a n×m chessboard. Queen’s position right now is (x,y).
Queen is the most powerful chess. It can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally (in all eight directions).
Bad Queen is a greedy queen. It wants to travel around all the blocks on the chessboard, but don’t want to take too many moves to make that happen. Please devise a route such that Bad Queen can visit all the blocks on the chessboard in exactly nm−1 moves. The current position is considered as visited.
Input
The input contains four space-separated integers n,m,x,y (1≤x≤n≤100, 1≤y≤m≤100, nm>1).
Output
Output the move sequence in order. That is nm−1 lines. Each line contains a coordinate (x,y), separated with space, which is the position after the move.
x1 y1x2 y2⋮xnm−1 ynm−1
(xi,yi) must be a legal position on chessboard, which means 1≤xi≤n, 1≤yi≤m.
If there are multiple solutions available, you may output any of them.
Examples
Input
3 3 1 1
Output
3 3 1 3 2 3 2 1 3 1 2 2 1 2 3 2
Note
Here is the route in the example. 0 is the starting position, and 1 to 8 are the visiting orders.
题意:
皇后,走的是直线、斜线,一步可以走任意的格子数,但要按照一个方向走
皇后想遍历全部的方格,假定他一开始的放个已经被他遍历过了,那么我们就需要按顺序输出nm-1行,
每行表示一个方格的位置。答案可能有多种,任意输出一种即可
解析:
一开始以为用一个dfs一直往下搜就可以了,但是这里皇后一步可以走很多格,所以dfs不太行。
后来就开始疯狂WA,最后想到,从他开始位置的那一行开始,每到一行,就遍历这个行的全部方格,然后先从起始行往下面的行遍历,遍历完,再到没有遍历过的行开始往上遍历
代码写的有点烂....可以忽略
#include <cstdio>
#include <cstring>
#include <algorithm>
#define pb push_back
using namespace std;
typedef long long ll;
const int MAXN= 1e2+10;
const ll MOD = 19260817;
int n,m;
int x,y;
int vis[MAXN][MAXN];
int read(){
char c=getchar();int x=0,f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1; c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0'; c=getchar();}
return x*f;
}
int dir[8][2]={-1,0,0,1,1,0,0,-1,-1,-1,-1,1,1,1,1,-1};
void dfs(int x,int y)
{
/*int nx=x+dir[flag][0];
int ny=y+dir[flag][0];
if(nx>=1&&nx<=n&&ny>=1&&ny<=m)
dfs(nx,ny,flag);
else if(vis[nx][ny]==1)
return;
else
{*/
for(int i=0;i<4;i++)
{
//if(i==flag) continue;
int nx=x+dir[i][0];
int ny=y+dir[i][1];
if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&vis[nx][ny]==0)
{
printf("%d %d\n",nx,ny);
vis[nx][ny]=1;
dfs(nx,ny);
}
}
//}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&x,&y);
vis[x][y]=1;
int i;
int j=y;
for(int w=x;w<=n;w++)
{
if(!vis[w][j])
printf("%d %d\n",w,j),vis[w][j]=1;
int tmp=j;
if(j+1<=m)
{
for(i=j+1;i<=m;i++) if(!vis[w][i])printf("%d %d\n",w,i),vis[w][i]=1,tmp=i;
}
if(j-1>=1)
{
for(i=j-1;i>=1;i--) if(!vis[w][i])printf("%d %d\n",w,i),vis[w][i]=1,tmp=i;
}
j=tmp;
}
for(int w=x-1;w>=1;w--)
{
if(!vis[w][j])
printf("%d %d\n",w,j),vis[w][j]=1;
int tmp=j;
if(j+1<=m)
{
for(i=j+1;i<=m;i++) if(!vis[w][i])printf("%d %d\n",w,i),vis[w][i]=1,tmp=i;
}
if(j-1>=1)
{
for(i=j-1;i>=1;i--) if(!vis[w][i])printf("%d %d\n",w,i),vis[w][i]=1,tmp=i;
}
j=tmp;
}
return 0;
}