C++
\nunordered_map<int,unordered_map<string,int>> dp;\n    int getMaxScore(auto curItr ,auto &end , string &visitedHash){\n        \n        int maxScore = 0;\n   
```\nunordered_map<int,unordered_map<string,int>> dp;\n    int getMaxScore(auto curItr ,auto &end , string &visitedHash){\n        \n        int maxScore = 0;\n        if(curItr!=end){ \n            int key = curItr->first;\n            if(dp.find(key)!=dp.end() &&  dp[key].find(visitedHash)!=dp[key].end())\n                return dp[key][visitedHash];\n            \n            unordered_set<int> &idxSet = curItr->second;\n            ++curItr;\n\n            for(int idx : idxSet){\n                if(visitedHash[2*idx+1] == \'#\'){\n                    visitedHash[2*idx+1] = \'O\' ;\n                    maxScore = max(maxScore,key+getMaxScore(curItr,end , visitedHash));\n                    visitedHash[2*idx+1] = \'#\' ;\n                }\n            }\n            \n            maxScore = max(maxScore,getMaxScore(curItr,end , visitedHash));\n            return dp[key][visitedHash] = maxScore;\n        }\n        \n        return maxScore;\n    }\n    \n    \n    int maxScore(vector<vector<int>>& grid) {\n       unordered_map<int,unordered_set<int>> reverseIndexMap;\n        \n       string visitedHash = "" ;\n       dp.clear();\n       for(int i = 0 ; i<grid.size();i++){\n            visitedHash+=\'-\';\n            visitedHash+= \'#\' ;\n       }\n        for(int i = 0 ; i<grid.size() ;i++){\n             for(int j = 0 ; j<grid[0].size() ;j++){\n                 reverseIndexMap[grid[i][j]].insert(i);\n            }\n            \n        }\n        \n         auto it = reverseIndexMap.begin();\n         auto end = reverseIndexMap.end();\n         return getMaxScore(it ,end, visitedHash);;\n     }\n```\n
[]