PAT 1068. 万绿丛中一点红(20)

就想知道同样的题,同样的思路,为什么c++就可以,而java不可以呢,真的是改得烦躁啊!!!

就是想知道为什么啊?如果有哪位大神看出来了,欢迎指正

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		String[] firstLine = scanner.nextLine().split(" ");
		int N = Integer.parseInt(firstLine[1]);
		int M = Integer.parseInt(firstLine[0]);
		int TOL = Integer.parseInt(firstLine[2]);
		int[][] index = {{-1, -1},{-1, 0},{-1,1},{0, -1},{0, 1},{1, -1},{1, 0},{1, 1}};
		
		int[][] pixels = new int[N + 1][M + 1];
		Map<Integer, Integer[]> unique = new HashMap<>();
		for(int i = 1; i != N + 1; i ++){
			String[] line = scanner.nextLine().split(" ");
			for (int j = 0; j != M; j++) {
				pixels[i][j + 1] = Integer.parseInt(line[j]);
				if (unique.containsKey(pixels[i][j + 1])) {
					unique.remove(pixels[i][j + 1]);
				}else {
					Integer[] temp = {i, j + 1};
					unique.put(pixels[i][j + 1], temp);
				}
			}
		}
		scanner.close();
		
		int count = unique.size();
		for(Entry<Integer, Integer[]> entry: unique.entrySet()){
			int flag = 1;
			for(int[] temp:index){
				int x = entry.getValue()[0] + temp[0];
				int y = entry.getValue()[1] + temp[1];
				if (x != 0 && y != 0 && x != (N + 1) && y != (M + 1)) {
					if (Math.abs(entry.getKey()-pixels[x][y]) <= TOL) {
						flag = 0;
					}
				}
			}
			if (flag == 0) {
				unique.put(entry.getKey(), null);
				count --;
			}
		}
		
		if (count == 1) {
			for(Entry<Integer, Integer[]> entry: unique.entrySet()){
				if (entry.getValue() != null) {
					System.out.print("(" + entry.getValue()[1] +", "+entry.getValue()[0] + ")" + ": " + entry.getKey());
				}
			}
		}else if (count > 1) {
			System.out.print("Not Unique");
		}else{
			System.out.print("Not Exist");
		}
	}
}
运行结果:

别人的c++代码,是能够完全正确的!!!

代码地址:http://blog.csdn.net/qq_34594236/article/details/63692920


#include<cstdio>
#include<iostream>
#include<cstring>
#include<map>
#include<cmath>
using namespace std;

map<int, int> vis;
int s[1001][1001];
int n, m ,tol;
int dir[8][2] = {1,0, -1,0, 0,1, 0,-1, 1,1, 1,-1, -1,1, -1,-1};
//判断是否大于阈值 
bool check(int x, int y)
{
	for(int i=0 ;i<8 ;i++){
		int xx = x + dir[i][0];
		int yy = y + dir[i][1];
		if(xx>=0 && xx<n && yy<m && yy>=0 && abs(s[xx][yy]-s[x][y])<=tol ) return false; 
	}
	return true;
}

int main(){
	cin>>m>>n>>tol;
	
	for(int i=0 ;i<n ;i++){
		for(int j=0 ;j<m ;j++){
			cin>>s[i][j];
			vis[s[i][j]] ++;  	
		}
	}
	//cnt记录只出现一次的数字的个数
	//x y记录坐标 
	int cnt = 0;
	int x, y;
	for(int i=0 ;i<n ;i++){
		for(int j=0 ;j<m ;j++){
			if(vis[s[i][j]]==1 && check(i,j)){
				cnt++;
				x = i;
				y = j;
			}	
		}
	}
	
	if(cnt==1){
		printf("(%d, %d): %d\n",y+1, x+1, s[x][y]);
	}
	else if(cnt>1){
		puts("Not Unique");
	}
	else{
		puts("Not Exist");
	}
	
	return 0;
}


发布了29 篇原创文章 · 获赞 16 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/u011412768/article/details/68947572