|
| 1 | +package package1; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import utils.CommonUtils; |
| 9 | + |
| 10 | +public class LongestConsecutivePathInAMatrix { |
| 11 | + |
| 12 | + final int[] dirs = new int[]{0, 1, 0, -1, 0}; |
| 13 | + |
| 14 | + public int[] longestConsecutivePath(int[][] grid){ |
| 15 | + List<Integer> resultList = new ArrayList(); |
| 16 | + Map<Integer, List<Integer>> map = new HashMap(); |
| 17 | + if(grid == null || grid.length == 0) return new int[]{}; |
| 18 | + |
| 19 | + for(int i = 0; i < grid.length; i++){ |
| 20 | + for(int j = 0; j < grid[0].length; j++){ |
| 21 | + List<Integer> thisList = dfs(grid, i, j, map); |
| 22 | + if(thisList.size() > resultList.size()){ |
| 23 | + resultList.clear(); |
| 24 | + resultList.addAll(thisList); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + int[] result = new int[resultList.size()]; |
| 29 | + for(int i = 0; i < resultList.size(); i++){ |
| 30 | + result[i] = resultList.get(i); |
| 31 | + } |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + private List<Integer> dfs(int[][] grid, int row, int col, Map<Integer, List<Integer>> map) { |
| 36 | + if(map.containsKey(grid[row][col])) return map.get(grid[row][col]); |
| 37 | + List<Integer> thisList = new ArrayList(); |
| 38 | + thisList.add(grid[row][col]); |
| 39 | + List<Integer> max = new ArrayList(); |
| 40 | + for(int i = 0; i < 4; i++){ |
| 41 | + int nextRow = row+dirs[i]; |
| 42 | + int nextCol = col+dirs[i+1]; |
| 43 | + if(nextRow < 0 || nextRow >= grid.length || nextCol < 0 || nextCol >= grid[0].length || grid[nextRow][nextCol]-1 != grid[row][col]) continue; |
| 44 | + if(grid[nextRow][nextCol]-1 == grid[row][col]){ |
| 45 | + List<Integer> nextList = dfs(grid, nextRow, nextCol, map); |
| 46 | + if(!nextList.isEmpty() && max.size() < nextList.size()) { |
| 47 | + max.clear(); |
| 48 | + max.addAll(nextList); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + thisList.addAll(max); |
| 53 | + map.put(grid[row][col], thisList); |
| 54 | + return thisList; |
| 55 | + } |
| 56 | + |
| 57 | + public static void main(String...args){ |
| 58 | + LongestConsecutivePathInAMatrix test = new LongestConsecutivePathInAMatrix(); |
| 59 | +// int[][] grid = new int[][]{ |
| 60 | +// {1, 2, 13, 5}, |
| 61 | +// {11, 10, 9, 6}, |
| 62 | +// {3, 4, 8, 7}, |
| 63 | +// {12, 14, 15, 16}, |
| 64 | +// }; |
| 65 | + |
| 66 | + int[][] grid = new int[][]{ |
| 67 | + {2, 3}, |
| 68 | + {1, 4}, |
| 69 | + }; |
| 70 | + int[] result = test.longestConsecutivePath(grid); |
| 71 | + CommonUtils.printArray(result); |
| 72 | + } |
| 73 | +} |
0 commit comments