|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Find the longest increasing(increasing means one step) sequence in an |
| 5 | + * integer matrix in 4 directions (up down left right), return the sequence |
| 6 | + * |
| 7 | + * For Example: |
| 8 | + * |1 2 3 4| |
| 9 | + * |8 7 6 5| |
| 10 | + * |
| 11 | + * Output: |
| 12 | + * [1, 2, 3, 4, 5, 6, 7, 8] |
| 13 | + * |
| 14 | + * Tags: DP, DFS |
| 15 | + */ |
| 16 | +class LongestIncreasingSequenceInMat { |
| 17 | + public static void main(String[] args) { |
| 18 | + LongestIncreasingSequenceInMat l = new LongestIncreasingSequenceInMat(); |
| 19 | + int[][] mat = { |
| 20 | + {1, 2, 3, 4}, |
| 21 | + {8, 7, 6, 5}, |
| 22 | + {9, 10, 11, 12} |
| 23 | + }; |
| 24 | + System.out.println(Arrays.toString(l.longest(mat))); |
| 25 | + } |
| 26 | + |
| 27 | + public static final int[][] DIRS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 28 | + int[][] cache; |
| 29 | + |
| 30 | + /** |
| 31 | + * DP |
| 32 | + * d[i][j] = max{d[i+1][j], d[i-1][j], d[i][j+1], d[i][j-1]} + 1 |
| 33 | + */ |
| 34 | + public int[] longest(int[][] mat) { |
| 35 | + int[] res = new int[]{}; |
| 36 | + if (mat == null || mat.length == 0 || mat[0].length == 0) return res; |
| 37 | + int m = mat.length; |
| 38 | + int n = mat[0].length; |
| 39 | + cache = new int[m][n]; |
| 40 | + int maxStart = 0; |
| 41 | + int maxPath = 0; |
| 42 | + for (int i = 0; i < m; i++) |
| 43 | + for (int j = 0; j < n; j++) { |
| 44 | + int path = dfs(i, j, mat); |
| 45 | + if (path > maxPath) { |
| 46 | + maxStart = mat[i][j]; |
| 47 | + maxPath = path; |
| 48 | + } |
| 49 | + } |
| 50 | + res = new int[maxPath]; |
| 51 | + // TODO recover the path, from maxStart with maxPath |
| 52 | + for (int i = 0; i < maxPath; i++) res[i] = maxStart + i; |
| 53 | + return res; |
| 54 | + } |
| 55 | + |
| 56 | + private int dfs(int i, int j, int[][] mat) { |
| 57 | + if (cache[i][j] != 0) return cache[i][j]; // has cache |
| 58 | + int m = mat.length; |
| 59 | + int n = mat[0].length; |
| 60 | + for (int[] d : DIRS) { // search 4 directions |
| 61 | + int ni = i + d[0]; // get next coordinates |
| 62 | + int nj = j + d[1]; |
| 63 | + if (ni >= 0 && ni < m && nj >= 0 && nj < n |
| 64 | + && mat[ni][nj] == mat[i][j] + 1) { |
| 65 | + // if dfs(ni, nj) is bigger, update cache[i][j] |
| 66 | + cache[i][j] = Math.max(cache[i][j], dfs(ni, nj, mat)); |
| 67 | + } |
| 68 | + } |
| 69 | + return ++cache[i][j]; // add cache[i][j] by 1 and return! |
| 70 | + } |
| 71 | +} |
0 commit comments