|
| 1 | +packagepackage1; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.HashMap; |
| 5 | +importjava.util.List; |
| 6 | +importjava.util.Map; |
| 7 | + |
| 8 | +importutils.CommonUtils; |
| 9 | + |
| 10 | +publicclassLongestConsecutivePathInAMatrix { |
| 11 | + |
| 12 | +finalint[]dirs =newint[]{0,1,0, -1,0}; |
| 13 | + |
| 14 | +publicint[]longestConsecutivePath(int[][]grid){ |
| 15 | +List<Integer>resultList =newArrayList(); |
| 16 | +Map<Integer,List<Integer>>map =newHashMap(); |
| 17 | +if(grid ==null ||grid.length ==0)returnnewint[]{}; |
| 18 | + |
| 19 | +for(inti =0;i <grid.length;i++){ |
| 20 | +for(intj =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 =newint[resultList.size()]; |
| 29 | +for(inti =0;i <resultList.size();i++){ |
| 30 | +result[i] =resultList.get(i); |
| 31 | + } |
| 32 | +returnresult; |
| 33 | + } |
| 34 | + |
| 35 | +privateList<Integer>dfs(int[][]grid,introw,intcol,Map<Integer,List<Integer>>map) { |
| 36 | +if(map.containsKey(grid[row][col]))returnmap.get(grid[row][col]); |
| 37 | +List<Integer>thisList =newArrayList(); |
| 38 | +thisList.add(grid[row][col]); |
| 39 | +List<Integer>max =newArrayList(); |
| 40 | +for(inti =0;i <4;i++){ |
| 41 | +intnextRow =row+dirs[i]; |
| 42 | +intnextCol =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 | +returnthisList; |
| 55 | + } |
| 56 | + |
| 57 | +publicstaticvoidmain(String...args){ |
| 58 | +LongestConsecutivePathInAMatrixtest =newLongestConsecutivePathInAMatrix(); |
| 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 =newint[][]{ |
| 67 | + {2,3}, |
| 68 | + {1,4}, |
| 69 | + }; |
| 70 | +int[]result =test.longestConsecutivePath(grid); |
| 71 | +CommonUtils.printArray(result); |
| 72 | + } |
| 73 | +} |