Routine calculations - 916 ms
Approach\nCheck every 3*3, if it pass threshold, return avg, for every coordinate create avg sum and number of intersects, later it will be used for getting fin
# Approach\nCheck every 3*3, if it pass `threshold`, return `avg`, for every coordinate create `avg` sum and number of intersects, later it will be used for getting final result, use initial, if intersects is 0. \n\n# Code\n```\n/**\n * @param {number[][]} image\n * @param {number} threshold\n * @return {number[][]}\n */\nvar resultGrid = function(image, threshold) {\n    const colsCount = image[0].length;\n    const result = Array.from({ length: image.length }, \n        () => Array.from({ length: colsCount }, () => new Array(2).fill(0)));\n\n    const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];\n    let rowMove, colMove;\n\n    const getAvg = (row, col) => {\n        let sum = 0;\n        for (let i = 0; i < 3; ++i) {\n            for (let j = 0; j < 3; ++j) {\n                sum += image[row + i][col + j];\n                for (const [r, c] of dirs) {\n                    rowMove = row + i + r;\n                    colMove = col + j + c;\n                    if (rowMove >= row && rowMove < row + 3 && colMove >= col && colMove < col + 3 && \n                        Math.abs(image[row + i][col + j] - image[rowMove][colMove]) > threshold) {\n                            return -1;\n                    }\n                }\n            }\n        }\n\n        return Math.floor(sum / 9);\n    };\n\n    const rows = image.length - 2;\n    const cols = colsCount - 2;\n    let avg;\n\n    for (let i = 0; i < rows; ++i) {\n        for (let j = 0; j < cols; ++j) {\n            avg = getAvg(i, j);\n            if (avg !== -1) {\n                for (let k = 0; k < 3; ++k) {\n                    for (let z = 0; z < 3; ++z) {\n                        result[i + k][j + z][0] += avg;\n                        ++result[i + k][j + z][1];\n                    }\n                }\n            }\n        }\n    }\n\n    for (let i = 0; i < image.length; ++i) {\n        for (let j = 0; j < colsCount; ++j) {\n            result[i][j] = result[i][j][1] === 0 ? image[i][j] : Math.floor(result[i][j][0] / result[i][j][1]);\n        }\n    }\n\n    return result;\n};\n```
['JavaScript']