PAT Basic Level 1068 万绿丛中一点红 解题思路及AC代码 v1.0

1. 题目简述及在线测试位置

1.1 给定一组数字(以矩阵形式呈现),找到符合如下条件的数字:该数字在矩阵中仅出现一次 且 该数字与周围数字的差值大于给定数
1.2 在线测试位置: 1068 万绿丛中一点红

2. 基本思路

2.1 通过二维数组a 存储数字矩阵,通过一维数组only 标示数字在矩阵中是否仅出现一次

#define MAX 1001 //矩阵的行列数<=1000、行列编号从1开始
#define ValueMax 16777216 //数值范围是[0,2^24]

int a[MAX][MAX];
short* only = (short*)malloc(sizeof(short) * ValueMax); //若使用int类型 内存会超限

2.2 数据存储完毕后,进行判定:剔除在矩阵中出现多次的数字 以及 与周围数字的差值小于等于给定数的数字(这里的差值需要转换为绝对值)
2.3 注意:矩阵的边缘点也需要判定(该点周围的数字并非是8个)

3. 完整AC代码

#include <stdlib.h> //malloc()
#include <iostream>
using namespace std;

#define MAX 1001
#define ValueMax 16777216

int Abs(int n);

int main()
{
	int Column, Row, Diff, Value;
	int Flag = 0, C = -1, R = -1; //记录结果:符合条件的数字数 对应的列 对应的行
	cin >> Column >> Row >> Diff;

	int a[MAX][MAX]; //Array a is used to store Data.

	//int only[ValueMax] = {0}; //only is used to judge repeat.
	short* only = (short*)malloc(sizeof(short) * ValueMax);//若使用int 内存会超限
	for (int i = 0; i < ValueMax; i++)
		only[i] = 0;

	for (int i = 1; i <= Row; i++)
	{
		for (int j = 1; j <= Column; j++)
		{
			cin >> Value;
			a[i][j] = Value;
			only[Value]++; //标注颜色是否唯一
		}
	}

	for (int i = 1; i <= Row; i++)
	{
		for (int j = 1; j <= Column; j++)
		{
			if (only[a[i][j]] > 1) //repeated colour is out!
				continue;

			if (j - 1 >= 1 && Abs(a[i][j] - a[i][j - 1]) <= Diff)
				continue;
			if (j + 1 <= Column && Abs(a[i][j] - a[i][j + 1]) <= Diff)
				continue;
			if (i - 1 >= 1 && Abs(a[i][j] - a[i - 1][j]) <= Diff)
				continue;
			if (i + 1 <= Row && Abs(a[i][j] - a[i + 1][j]) <= Diff)
				continue;
			if (i - 1 >= 1 && j - 1 >= 1 && Abs(a[i][j] - a[i - 1][j - 1]) <= Diff)
				continue;
			if (i + 1 <= Row && j - 1 >= 1 && Abs(a[i][j] - a[i + 1][j - 1]) <= Diff)
				continue;
			if (i - 1 >= 1 && j + 1 <= Column && Abs(a[i][j] - a[i - 1][j + 1]) <= Diff)
				continue;
			if (i + 1 <= Row && j + 1 <= Column && Abs(a[i][j] - a[i + 1][j + 1]) <= Diff)
				continue;
			
			R = i;
			C = j;
			Flag++;
		}
	}
	if (Flag==0)
		cout << "Not Exist";
	else if (Flag == 1)
		cout << "(" << C << ", " << R << "): " << a[R][C];
	else
		cout << "Not Unique";

	return 0;
}

int Abs(int n)
{
	if (n >= 0)
		return n;
	else
		return n * -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值