1068 万绿丛中一点红 - PAT (Basic Level) Practice (中文) (pintia.cn)
x坐标的走法:
y坐标的走法::
#include<bits/stdc++.h>
using namespace std;
const int N=1000;
int m,n,tol;
int a[N][N];
int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
bool check(int i,int j)
{
for(int k=0;k<8;k++)
{
int tx=i+dir[k][0];
int ty=j+dir[k][1];
if(tx>=0&&tx<m&&ty>=0&&ty<n&&a[i][j]-a[tx][ty]>=0-tol&&a[i][j]-a[tx][ty]<=tol)return false;
}
return true;
}
int main()
{
cin>>m>>n>>tol;
int cnt=0,x=0,y=0;
map<int,int>mapp;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>a[i][j];
mapp[a[i][j]]++;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mapp[a[i][j]]==1&&check(i,j)==true)
{
cnt++;
x=i+1;
y=j+1;
}
}
}
if(cnt==1)printf("(%d, %d): %d",y,x,a[x-1][y-1]);
else if(cnt==0)
printf("Not Exist");
else printf("Not Unique");
return 0;
}
第二种方法
#include<bits/stdc++.h>
using namespace std;
int n,m,tol;
int cnt,x,y;
int a[1005][1005];
map<int,int>mp;
int dx[8] = { 0,1,1,1,0,-1,-1,-1 };
int dy[8] = { 1,1,0,-1,-1,-1,0,1 };
bool check(int x,int y)
{
for(int i=0;i<8;i++)
{
int tempx=dx[i]+x;
int tempy=dy[i]+y;
if(tempx<0||tempx>=n||tempy<0||tempy>=m)continue;
if(abs(a[tempx][tempy]-a[x][y])<=tol)return false;
}
return true;
}
int main()
{
cin>>m>>n>>tol; //m是列,n是行 (看样例)
for(int i=0;i<n;i++) //n行m列
{
for(int j=0;j<m;j++)
{
cin>>a[i][j];
mp[a[i][j]]++;
}
}
for(int i=0;i<n;i++) //n行m列
{
for(int j=0;j<m;j++)
{
if(mp[a[i][j]]>1)continue; //如果一个点·出现了多次就跳过这个点
if(check(i,j)) //只出现一次的点进行检查
{
cnt++;
x=i,y=j;
}
}
}
if(cnt==0)cout<<"Not Exist";
else if(cnt==1)printf("(%d, %d): %d",y+1,x+1,a[x][y]); //注意要先输出列再输出行 ,编号从1开始,所以还要再加1
else cout<<"Not Unique";
return 0;
}