题目描述
一个迷宫由 n 行 m 列格子组成,给定其中的一个位置坐标 (x,y),求出其上下左右相邻点的坐标。
注意:输出时按照右下左上的方向输出。
输入格式
输入仅一行,包含 4 个整数 n,m,x,y。
0<n,m≤1000;1≤x≤n,1≤y≤m
输出格式
输出有 4 行,按照右下左上的方向输出 (x,y) 这个点的 4 个相邻点。每一行输出两个数,分别包含行坐标和列坐标,其间用一个空格隔开。
注意:如果其中某个相邻点越界了则输出 NA。
样例组输入#1
5 6 2 1
样例组输出#1
2 2 3 1 NA 1 1
方法一:
#include <iostream>
using namespace std;
int main() {
int n, m, x, y;
cin >> n >> m >> x >> y;
if (y + 1 <= m)
cout << x << " " << y + 1 << endl;
else
cout << "NA" << endl;
if (x + 1 <= n)
cout << x + 1 << " " << y << endl;
else
cout << "NA" << endl;
if (y - 1 >= 1)
cout << x << " " << y - 1 << endl;
else
cout << "NA" << endl;
if (x - 1 >= 1)
cout << x - 1 << " " << y << endl;
else
cout << "NA" << endl;
return 0;
}
方法二:
#include <iostream>
using namespace std;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int main(){
int n,m,x,y;
cin>>n>>m>>x>>y;
for(int i=0;i<4;i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(nx<1||nx>n||ny<1||ny>m){
cout<<"NA"<<endl;
}
else {
cout<<nx<<" "<<ny<<endl;
}
}
return 0;
}