✅Simulation || ⚡BruteForce || 🔥Cleanest Code
Complexity\n\n- Time complexity:\nO(m * n * 9)\n\n- Space complexity:\nO(m * n)\n\n\n# Code\n## PLease Upvote if it helps\uD83E\uDD17\n\nclass Solution {\npubli
# Complexity\n```\n- Time complexity:\nO(m * n * 9)\n\n- Space complexity:\nO(m * n)\n```\n\n# Code\n## PLease Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n    pair<int, int> isValid(int i, int j, int m, int n, vector<vector<int>>& image, int threshold){\n        if(i + 2 >= m || j + 2 >= n)\n            return {false, 0};\n        int sum = 0;\n        for(int h = i ; h < i + 3 ; h++){\n            for(int k = j ; k < j + 3 ; k++){\n                if(k != j + 2 && (abs(image[h][k] - image[h][k + 1]) <= threshold) || (k == j + 2)){\n                    if(h != i + 2){\n                        if(abs(image[h][k] - image[h + 1][k]) > threshold)\n                            return {false, 0};\n                    }\n                }\n                else\n                    return {false, 0};\n                sum += image[h][k];\n            }\n        }\n        return {true, sum};\n    }\n        \n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        int m = image.size(), n = image[0].size();\n        vector<vector<int>> res(m, vector<int>(n));\n        map<pair<int, int>, vector<int>> mp;  \n        for(int i = 0 ; i < m ; i++){\n            for(int j = 0 ; j < n ; j++){\n                auto [x, y] = isValid(i, j, m, n, image, threshold);\n                if(x){\n                    for(int l = i ; l < i + 3 ; l++){\n                        for(int k = j ; k < j + 3 ; k++){\n                            mp[{l, k}].push_back(y / 9);\n                        }\n                    }   \n                }\n            }\n        }\n        for(int i = 0 ; i < m ; i++){\n            for(int j = 0 ; j < n ; j++){\n                int tot = 0, cnt = mp[{i, j}].size();\n                for(auto it : mp[{i, j}])\n                    tot += it;\n                if(cnt)\n                    res[i][j] = tot / cnt;\n                else\n                    res[i][j] = image[i][j];\n            }\n        }\n        return res;\n    }\n};\n```
['Ordered Map', 'Matrix', 'Simulation', 'C++']