题目:http://poj.org/problem?id=1088
花了好久才写完的。。。脑子不好使啊
- package dynamicprogramming;
- /**
- * 滑雪问题
- * array 数组表示高山
- * @author dongdong
- *
- */
- public class Skiing {
- private static int Max = 99; //加边框,这样后面无需边界判断
- static int[][] array2 =
- {{1 , 2, 3, 4, 5},
- {16, 17, 18, 19, 6},
- {15, 24, 25, 20, 7},
- {14, 23, 22, 21, 8},
- {13, 12, 11, 10, 9}};
- static int[][] array =
- {{22 ,21, 20, 19, 18},
- {16, 17, 18, 19, 17},
- {15, 24, 25, 20, 13},
- { 6, 3, 2, 14, 8},
- { 5, 4, 1, 10, 9}};
- static int row = 5;
- static int column = 5;
- static int[][] len = new int[row+2][column+2];//每一点能滑雪的最长距离
- static boolean[][] flag = new boolean[row+2][column+2];//标记是否该点的最长距离已经被计算过
- static{
- for (int i = 0; i < flag.length; i++) {
- for (int j = 0; j < flag[0].length; j++) {
- flag[i][j] = false;
- }
- }
- }
- static int[][] orients1 ={{0,1},{1,0},{0,-1},{-1,0}};
- static int[][] orients ={{0,-1},{-1,0},{0,1},{1,0}}; //四个方向,先后没有关系
- public static void main(String[] args){
- array = wrap(array,row,column);
- print(array);
- int d = dpCalLongestDistance(row,column);
- System.out.println("longest distance is :"+ d);
- }
- /**
- * 动态规划找最长路径
- * @param row
- * @param column
- * @return
- */
- private static int dpCalLongestDistance(int row, int column) {
- int longest = 0;
- for (int i = 1; i <= row; i++)
- for (int j = 1; j <= column; j++) {
- len[i][j]= dp(i,j);
- if(len[i][j]>longest)
- longest= len[i][j];
- }
- print(len);
- return longest;
- }
- /**
- *
- * len[i][j]= max{len[周围]} + 1, each len[k]<len[i][j]
- * 1, all(len[周围])>len[i][j]
- * @param i
- * @param j
- * @return
- */
- private static int dp(int i, int j) {
- int max = 1;
- for (int k = 0; k < 4; k++) {
- if (array[i][j] > array[i + orients[k][0]][j + orients[k][1]]) {
- if (!flag[i + orients[k][0]][j + orients[k][1]]) {
- int tmp = dp(i + orients[k][0], j + orients[k][1]) + 1;
- if (tmp > max)
- max = tmp;
- } else
- max = len[i + orients[k][0]][j + orients[k][1]] + 1;
- }
- }
- return max;
- }
- public static void print(int[][] array){
- for(int i=0;i<array.length;i++){
- for (int j = 0; j < array[0].length; j++) {
- if(array[i][j]/10>0)
- System.out.print(array[i][j]+" " );
- else
- System.out.print(" "+array[i][j]+" " );
- }
- System.out.println();
- }
- }
- private static int[][] wrap(int[][] mountains,int row, int column) {
- int[][] m2 = new int[row+2][column+2];
- for(int i = 0;i<row+2;i++){
- m2[i][0]=Max;
- m2[i][column+1]=Max;
- }
- for(int j = 0;j<column+2;j++){
- m2[0][j]=Max;
- m2[row+1][j]=Max;
- }
- for(int i=1;i<=row;i++)
- for (int j =1; j <=column; j++)
- m2[i][j]=mountains[i-1][j-1];
- return m2;
- }
- }