题目:http://acm.pku.edu.cn/JudgeOnline/problem?id=1014
思路:DP,走过一个点,那么记住如果从这个点开始的最大长度,减少冗余。
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class Main {
- int[][] h;
- int[][] used;
- int max;
- public static void main(String[] args) throws IOException {
- new Main();
- }
- public Main() throws IOException {
- BufferedReader read = new BufferedReader(new InputStreamReader(
- System.in));
- String[] s;
- s = read.readLine().split(" ");
- int r = Integer.parseInt(s[0]);
- int c = Integer.parseInt(s[1]);
- h = new int[r][c];
- used = new int[r][c];
- max = 0;
- for (int i = 0; i < r; i++) {
- s = read.readLine().split(" ");
- for (int j = 0; j < c; j++) {
- h[i][j] = Integer.parseInt(s[j]);
- }
- }
- for (int i = 0; i < r; i++) {
- for (int j = 0; j < c; j++) {
- int tmax = 0;
- tmax = move(i, j);
- if (tmax > max) {
- max = tmax;
- }
- }
- }
- System.out.println(max);
- }
- public int move(int r, int c) {
- if (used[r][c] != 0) {
- return used[r][c];
- } else {
- int tmax = 1;
- int t;
- if (r - 1 >= 0 && h[r][c] > h[r - 1][c]) {
- t = move(r - 1, c);
- if (t + 1 > tmax) {
- tmax = t + 1;
- }
- }
- if (r + 1 < h.length && h[r][c] > h[r + 1][c]) {
- t = move(r + 1, c);
- if (t + 1 > tmax) {
- tmax = t + 1;
- }
- }
- if (c - 1 >= 0 && h[r][c] > h[r][c - 1]) {
- t = move(r, c - 1);
- if (t + 1 > tmax) {
- tmax = t + 1;
- }
- }
- if (c + 1 < h[0].length && h[r][c] > h[r][c + 1]) {
- t = move(r, c + 1);
- if (t + 1 > tmax) {
- tmax = t + 1;
- }
- }
- used[r][c] = tmax;
- return tmax;
- }
- }
- }