package noj_skiing; import java.util.*;
import java.math.*; public class Main { public static void main(String[] args) {
Solution s = new Solution();
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] result = new int[N];
for(int i = 0; i < N; i++) {
int rowNum = sc.nextInt();
int colNum = sc.nextInt();
int[][] info = new int[rowNum][colNum];
for(int r = 0; r < rowNum; r++) {
for(int c = 0; c < colNum; c++) {
info[r][c] = sc.nextInt();
}
}
result[i] = s.getResult(info, rowNum, colNum);
}
sc.close();
for(int i : result) {
System.out.println(i);
}
} }
class Solution {
public int getResult(int[][] info, int rowNum, int colNum) {
int max = 0;
int[][] states = new int[rowNum][colNum]; //make sure equal 0 all
for(int r = 0; r < rowNum; r++) {
for(int c = 0; c < colNum; c++) {
max = Math.max(max, getMaxLength(info, r, c, rowNum, colNum, states));
}
}
return max;
}
public int getMaxLength(int[][] info, int row, int col, int rowNum, int colNum, int[][] states) { if(row < 0 || row >= rowNum || col < 0 || col >= colNum) //如果输入的坐标越界的处理
return 0;
if(states[row][col] != 0) //所求位置的最大长度求过
return states[row][col]; int nextStep = findNextStep(info, row, col, rowNum, colNum);
if(nextStep == 0) //所求位置在队尾
return states[row][col] = 1;
int maxLengthUp = (nextStep & 8) == 8 ? getMaxLength(info, row - 1, col, rowNum, colNum, states) : 0;
int maxLengthDown = (nextStep & 4) == 4 ? getMaxLength(info, row + 1, col, rowNum, colNum, states) : 0;
int maxLengthLeft = (nextStep & 2) == 2 ? getMaxLength(info, row, col - 1, rowNum, colNum, states) : 0;
int maxLengthRight = (nextStep & 1) == 1 ? getMaxLength(info, row, col + 1, rowNum, colNum, states) : 0; return max_4(maxLengthUp, maxLengthDown, maxLengthLeft, maxLengthRight) + 1;
}
public int findNextStep(int[][] info, int row, int col, int rowNum, int colNum) {
int result = 0; if(row != 0 && info[row - 1][col] < info[row][col]) //up
result |= 8;
if(row != rowNum - 1 && info[row + 1][col] < info[row][col]) //down
result |= 4;
if(col != 0 && info[row][col - 1] < info[row][col]) //left
result |= 2;
if(col != colNum - 1 && info[row][col + 1] < info[row][col]) //right
result |= 1; return result;
}
public int max_4(int i_1, int i_2, int i_3, int i_4) {
return Math.max(Math.max(i_1, i_2), Math.max(i_3, i_4));
}
}
感觉不是很难,思路一上来就可以想出来,具体一些细节的处理也没有很坑的地方。