Get Biggest Three Rhombus Sums in a Grid LeetCode solution in JavaScript
1var getBiggestThree = function (grid) {2const m = grid.length;3const n = grid[0].length;45const set = new Set();67for (let i = 0; i < m; ++i) {8for (let j = 0; j < n; ++j) {9let sum = grid[i][j];1011set.add(sum);1213let len = 1;14let row = i;15let col = j;1617while (withinBound(row + 1, col - 1)) {18++len;19++row;20--col;2122traverse(i, j, row, col, sum, len, 0, "botRight");23sum += grid[row][col];24}25}26}2728let max1;29let max2;30let max3;3132for (const num of set) {33if (max1 == null || num > max1) {34max3 = max2;35max2 = max1;36max1 = num;37} else if (max2 == null || num > max2) {38max3 = max2;39max2 = num;40} else if (max3 == null || num > max3) {41max3 = num;42}43}4445const res = [];4647if (max1) res[0] = max1;48if (max2) res[1] = max2;49if (max3) res[2] = max3;5051return res;5253function traverse(54destRow,55destCol,56currRow,57currCol,58totSum,59lenSize,60currLen,61currDir62) {63if (currRow === destRow && currCol === destCol) {64set.add(totSum);65return;66}6768totSum += grid[currRow][currCol];69++currLen;7071if (currDir === "botRight") {72if (currLen < lenSize) {73if (!withinBound(currRow + 1, currCol + 1)) return;7475traverse(76destRow,77destCol,78currRow + 1,79currCol + 1,80totSum,81lenSize,82currLen,83currDir84);85} else if (currLen === lenSize) {86if (!withinBound(currRow - 1, currCol + 1)) return;8788traverse(89destRow,90destCol,91currRow - 1,92currCol + 1,93totSum,94lenSize,951,96"topRight"97);98}99} else if (currDir === "topRight") {100if (currLen < lenSize) {101if (!withinBound(currRow - 1, currCol + 1)) return;102103traverse(104destRow,105destCol,106currRow - 1,107currCol + 1,108totSum,109lenSize,110currLen,111"topRight"112);113} else if (currLen === lenSize) {114if (!withinBound(currRow - 1, currCol - 1)) return;115116traverse(117destRow,118destCol,119currRow - 1,120currCol - 1,121totSum,122lenSize,1231,124"topLeft"125);126}127} else if (currDir === "topLeft") {128if (!withinBound(currRow - 1, currCol - 1)) return;129130traverse(131destRow,132destCol,133currRow - 1,134currCol - 1,135totSum,136lenSize,137currLen,138"topLeft"139);140}141}142143function withinBound(row, col) {144return row >= 0 && col >= 0 && row < m && col < n;145}146};