Advertisement
Guest User

Untitled

a guest
Feb 21st, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let directions = [[0, 1], [1, 0], [-1, 0], [0, -1]], curMax = 0, maxSteps = [0, 0, 0, 0];
  2.  
  3. let findMaxPath = (matrix) => {
  4.     let coords = [], max = 0;
  5.     for (let i = 0; i < matrix.length; i++) {
  6.         max = Math.max(max, ...matrix[i]);
  7.         curMax = max;
  8.     }
  9.  
  10.     for (let i = 0; i < matrix.length; i++) {
  11.         for (let j = 0; j < matrix[0].length; j++) {
  12.             if (matrix[i][j] === max) {
  13.                 coords.push([i, j, matrix[i][j], -1, -1, 1]);
  14.             }
  15.         }
  16.     }
  17.  
  18.     for (let start of coords) {
  19.         traverse(start, matrix);
  20.     }
  21.    
  22.     return curMax;
  23.  
  24. };
  25.  
  26. let traverse = (start, matrix) => {
  27.     let [x, y, current, prevX, prevY, step] = start;
  28.     maxSteps[step - 1] = parseInt(current);
  29.     if (step === 4) {
  30.         if (parseInt(current) > curMax) {
  31.             curMax = parseInt(current);
  32.         }
  33.         return current;
  34.     }
  35.     for (let dir of directions) {
  36.         let nextX = x + dir[0], nextY = y + dir[1], nextStep = step + 1;
  37.         if (matrix[nextX] && matrix[nextX][nextY] && (nextX !== prevX || nextY !== prevY)) {
  38.             let nextCurrent = parseInt("" + current + matrix[nextX][nextY]);
  39.             if (nextCurrent >= maxSteps[step]) {
  40.                 let start = [nextX, nextY, "" + current + matrix[nextX][nextY], x, y, nextStep];
  41.                 traverse(start, matrix);
  42.             }
  43.         }
  44.     }
  45. };
  46.  
  47. let result = findMaxPath([
  48.     [9, 8, 7],
  49.     [9, 5, 4],
  50.     [2, 5, 3]
  51. ]);
  52.  
  53. console.log("answer", result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement