难点
不能直接用int类型的二维数组存储。考试时我就是这样,最后没能通过所有案例。
最后想到了学习的图数据存储就是map里套map 【Map<Integer, Map<Integer,Integer>>】 ,没想到真通过了。
代码肯定还能优化,只是我写了几个小时,,已经不想再看了。
代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CCF2019122 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int s[] = new int[5];
Map<Integer, Map<Integer,Integer>> map = new HashMap<Integer, Map<Integer,Integer>>();
Laji lajis[] = new Laji[n];
for(int i = 0; i<n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
Laji lj = new Laji(x,y);
lajis[i] = lj;
if(map.containsKey(x)) {
map.get(x).put(y,1);
}else {
Map map2 = new HashMap();
map2.put(y, 1);
map.put(x, map2);
}
}
// System.out.println(map);
sc.close();
for(int i = 0; i < n; i++) {
int x = lajis[i].getX();
int y = lajis[i].getY();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
if(map.containsKey(x)) {
Map map3 = new HashMap();
map3 = map.get(x);
if(map3.containsKey(y+1)) flag1 = true;
if(map3.containsKey(y-1)) flag2 = true;
}
if(map.containsKey(x-1)) {
Map map3 = new HashMap();
map3 = map.get(x-1);
if(map3.containsKey(y)) flag3 = true;
}
if(map.containsKey(x+1)) {
Map map3 = new HashMap();
map3 = map.get(x+1);
if(map3.containsKey(y)) flag4 = true;
}
if(flag1 && flag2 && flag3 && flag4) {
int score = 0;
if(map.containsKey(x+1)) {
Map map4 = new HashMap();
map4 = map.get(x+1);
if(map4.containsKey(y+1)) score += 1;
if(map4.containsKey(y-1)) score += 1;
}
if(map.containsKey(x-1)) {
Map map4 = new HashMap();
map4 = map.get(x-1);
if(map4.containsKey(y+1)) score += 1;
if(map4.containsKey(y-1)) score += 1;
}
s[score] += 1;
}
}
for(int i=0;i<5;i++) {
System.out.println(s[i]);
}
}
public static class Laji{
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Laji(int x, int y) {
this.x = x;
this.y = y;
}
}
}
结果
题目