两数是否相邻(adjacent) 题目描述 一个n行m列的数字队形,队形中的数两两各不相同,那么给定2个数,请你编程判断,这2个数是否相邻?
相邻的定义是:如果两个同学在上下左右的位置是挨在一起的,那么就算是相邻的。
比如:如下是一个3行4列数字队形。
8 2 3 4
5 6 7 1
9 10 11 12
那么这个队形中, 6和10两个就是相邻的。
输入 第1行有2个整数n和m,分别代表队形的行和列的值;
接下来n行,每行有m个整数;
第n+2行是1个整数s,表示有s对数需要查询是否相邻;
接下来有s行数,每行输入2个整数,代表要查询是否相邻的两个数。
输出 如果两个数是相邻的,请输出字符Y,否则请输出字符N。
样例输入 3 4 8 2 3 4 5 6 7 1 9 10 11 12 2 6 10 8 12 样例输出 Y N 数据规模: 30%的数据,s为1,n和m两者之一的值为1;
70%的数据n,m,s<=200;
100%的数据n,m<=1000,s<=11000,数列中的每一个数ai<=2000000;
我的代码:
#include <bits/stdc++.h>
using namespace std;
int n,m,a[2002][2002],s,maxn;
struct node{
int gs,x[51],y[51];
} b[4000001];
int main ()
{
cin>>n>>m;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
cin>>a[i][j],b[a[i][j]+2000000].gs++,b[a[i][j]+2000000].x[b[a[i][j]+2000000].gs]=i,b[a[i][j]+2000000].y[b[a[i][j]+2000000].gs]=j;
cin>>s;
for (int i=1;i<=s;i++)
{
int x,y,p=0;
cin>>x>>y;
for (int j=1;j<=b[x+2000000].gs;j++)
if (a[b[x+2000000].x[j]-1][b[x+2000000].y[j]]==y||a[b[x+2000000].x[j]+1][b[x+2000000].y[j]]==y||a[b[x+2000000].x[j]][b[x+2000000].y[j]-1]==y||a[b[x+2000000].x[j]][b[x+2000000].y[j]+1]==y)
{
p=1;
cout<<"Y\n";
break;
}
if (!p) cout<<"N\n";
}
return 0;
}