求出一个矩阵中最长递增路径

递归(深度优先遍历)

package Search;

import java.util.LinkedList;
import java.util.Stack;

public class LongestIncreasingPathInMatrix {
    /**
     * 寻找一个矩阵中最长增长路径
     * 深度搜索
     */
    public static int longestIncreasingInMatrix(int[][] matrix, LinkedList list){
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return 0;
        }
        int max = 1;
        boolean[][] flag = new boolean[matrix.length][matrix[0].length];
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(!flag[i][j]){
                    LinkedList tmp = new LinkedList<>();
                    int len = longest(matrix,i,j,tmp,flag);
                    if(len > max){
                        max = len;
                        while(!list.isEmpty()){
                            list.poll();
                        }
                        while(!tmp.isEmpty()) {
                            list.add(tmp.pollFirst());
                        }
                    }
                }
            }
        }
        return max == 1 ? 0 : max;

    }


   /* public static int longestIncreasing(int[][] matrix) {


    }*/
    public static int longest(int[][] matrix, int row, int col, LinkedList list, boolean[][] flag){
        int[][] go = {{0,-1},{-1,0},{0,1},{1,0}};
        flag[row][col] = true;
        int max = 1;
        LinkedList maxList = null;
        for(int i = 0; i < 4; i++){
            int newRow = row + go[i][0];
            int newCol = col + go[i][1];
            if(newRow >= 0 && newRow < matrix.length && newCol >= 0 && newCol < matrix[0].length
                    && matrix[newRow][newCol] > matrix[row][col]){
                LinkedList tmp = new LinkedList<>();
                int ans = longest(matrix, newRow, newCol, tmp, flag);
                if(ans + 1 > max){
                    max = ans + 1;
                    maxList = tmp;
                }
            }
        }
        list.addLast(matrix[row][col]);
        if(maxList != null) {
            while (!maxList.isEmpty()) {
                list.addLast(maxList.pollFirst());
            }
        }
        return max;
    }
    public static void main(String[] args){
        int[][] arr = {
                       {13,33,32,89,90},
                       {14,34,24,23,91},
                       {13,14,103,102,101}
                       };
        LinkedList list = new LinkedList<>();
        System.out.println(longestIncreasingInMatrix(arr,list));
        while(!list.isEmpty()){
            System.out.print(list.pollFirst() + " ");
        }
        System.out.println();
    }

}

 

你可能感兴趣的:(数据结构和算法)