题目:
对于计算机而言,颜色不过是像素点对应的一个 24 位的数值。现给定一幅分辨率为 M×N 的画,要求你找出万绿丛中的一点红,即有独一无二颜色的那个像素点,并且该点的颜色与其周围 8 个相邻像素的颜色差充分大。
输入格式:
输入第一行给出三个正整数,分别是 M 和 N(≤ 1000),即图像的分辨率;以及 TOL,是所求像素点与相邻点的颜色差阈值,色差超过 TOL 的点才被考虑。随后 N 行,每行给出 M 个像素的颜色值,范围在 [0,2^24) 内。所有同行数字间用空格或 TAB 分开。
输出格式:
在一行中按照 (x, y): color 的格式输出所求像素点的位置以及颜色值,其中位置 x 和 y 分别是该像素在图像矩阵中的列、行编号(从 1 开始编号)。如果这样的点不唯一,则输出 Not Unique;如果这样的点不存在,则输出 Not Exist。
输入样例 1:
8 6 200
0 0 0 0 0 0 0 0
65280 65280 65280 16711479 65280 65280 65280 65280
16711479 65280 65280 65280 16711680 65280 65280 65280
65280 65280 65280 65280 65280 65280 165280 165280
65280 65280 16777015 65280 65280 165280 65480 165280
16777215 16777215 16777215 16777215 16777215 16777215 16777215 16777215
输出样例 1:
(5, 3): 16711680
输入样例 2:
4 5 2
0 0 0 0
0 0 3 0
0 0 0 0
0 5 0 0
0 0 0 0
输出样例 2:
Not Unique
输入样例 3:
3 3 5
1 2 3
3 4 5
5 6 7
输出样例 3:
Not Exist
分析:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include<map>
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
//#define Max 100001
int color[1001][1001];//必须放在外层,不然在main里会返回巨大的异常值
int x,y,res;
int main(){
map<int,int> vis;
int i,j,n,m;
int tol;
scanf("%d %d %d",&m,&n,&tol);
for(i=0;i<n;i++){
for(j=0;j<m;j++){
scanf("%d",&color[i][j]);
vis[color[i][j]]++;
}
}
int flag=0;//用来计算是否是唯一的一个,如果最后仍旧为0那么就是不存在,1表示唯一,2表示多个然后退出循环
//i,j-->
//(i-1,j),(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j),(i+1,j-1),(i+1,j+1)
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(vis[color[i][j]]==1){
//i-1,j
if(i-1>=0){
if(abs(color[i][j]-color[i-1][j])<=tol)
continue;
}
if(i-1>=0&&j-1>=0){//(i-1,j-1)
if(abs(color[i][j]-color[i-1][j-1])<=tol)
continue;
}
if(i-1>=0&&j+1<m){//(i-1,j+1)
if(abs(color[i][j]-color[i-1][j+1])<=tol)
continue;
}
if(j-1>=0){//,(i,j-1)
if(abs(color[i][j]-color[i][j-1])<=tol)
continue;
}
if(j+1<m){//,(i,j+1),
if(abs(color[i][j]-color[i][j+1])<=tol)
continue;
}
if(i+1<n){//(i+1,j),
if(abs(color[i][j]-color[i+1][j])<=tol)
continue;
}
if(i+1<n&&j-1>=0){//(i+1,j-1),
if(abs(color[i][j]-color[i+1][j-1])<=tol)
continue;
}
if(i+1<n&&j+1<m){//(i+1,j+1)
if(abs(color[i][j]-color[i+1][j+1])<=tol)
continue;
}
flag++;
if(flag==2)//此数不唯一,退出
break;
x=i;
y=j;
}
}
}
if(flag==0)
printf("Not Exist");
else if(flag==2)
printf("Not Unique");
else
printf("(%d, %d): %d",y+1,x+1,color[x][y]);
}
AC:
- 注意有两个要求:
1.与周围像素明显差异。
2.此像素在所有的像素里独一无二 - 还有就是C++里map的使用
- 在dev定义大型的二维数组,超过760多的好像都会报异常,但只要放在main函数之外定义就没事,奇怪了