没看视频, 开始做本题, 数据过了17/20, 犯了一个错误, 就是bfs 时, 当不是山峰,也不是山谷的时候, 不能直接return, 需要把剩下的高度相同的地方遍历完。
import java.io.*;
import java.util.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static int N = 1010, row, col;
static int[][] a = new int[N][N];
static boolean[][] st = new boolean[N][N];
static boolean hasHigher = false, hasLower = false;
static int[][] dir = new int[][]{
{-1, 0}, {-1, 1}, {0, 1}, {1, 1},
{1, 0}, {1, -1}, {0, -1}, {-1, -1}};
public static void main(String[] args) throws Exception{
int n = Integer.valueOf(read.readLine());
row = col = n;
for(int i = 0; i < n; i++){
String[] ss = read.readLine().split(" ");
for(int j = 0; j < n; j++){
a[i][j] = Integer.valueOf(ss[j]);
}
}
int peak = 0, vally = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(!st[i][j]){
hasHigher = false; hasLower = false;
bfs(i, j);
if(!hasHigher) peak++;
if(!hasLower) vally++;
}
}
}
System.out.println(peak + " " + vally);
}
public static void bfs(int x, int y){
Queue<Integer> q = new LinkedList();
int ref = reflect(x, y);
int curNum = a[x][y];
q.offer(ref);
st[x][y] = true;
while(!q.isEmpty()){
int poll = q.poll();
int[] def = deflect(poll);
for(int i = 0; i < 8; i++){
int nx = def[0] + dir[i][0];
int ny = def[1] + dir[i][1];
if(nx < 0 || nx >= row || ny < 0 || ny >= col) continue;
if(a[nx][ny] != curNum){
if(a[nx][ny] > curNum) hasHigher = true;
else hasLower = true;
}else if(!st[nx][ny]) {
st[nx][ny] = true;
ref = reflect(nx, ny);
q.offer(ref);
}
}
}
}
public static int reflect(int x, int y){
return x * col + y;
}
public static int[] deflect(int a){
return new int[]{a / col, a % col};
}
}
看啥视频。。。。 直接硬做啊