- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 57 lines of C++ from the credited upstream file 1591.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 7 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1enum class State { kInit, kVisiting, kVisited };2 3class Solution {4 public:5 bool isPrintable(vector<vector<int>>& targetGrid) {6 constexpr int kMaxColor = 60;7 const int m = targetGrid.size();8 const int n = targetGrid[0].size();9 10 vector<unordered_set<int>> graph(kMaxColor + 1);11 12 for (int color = 1; color <= kMaxColor; ++color) {13 14 int minI = m;15 int minJ = n;16 int maxI = -1;17 int maxJ = -1;18 for (int i = 0; i < m; ++i)19 for (int j = 0; j < n; ++j)20 if (targetGrid[i][j] == color) {21 minI = min(minI, i);22 minJ = min(minJ, j);23 maxI = max(maxI, i);24 maxJ = max(maxJ, j);25 }26 27 for (int i = minI; i <= maxI; ++i)28 for (int j = minJ; j <= maxJ; ++j)29 if (targetGrid[i][j] != color)30 graph[color].insert(targetGrid[i][j]);31 }32 33 vector<State> states(kMaxColor + 1);34 35 for (int color = 1; color <= kMaxColor; ++color)36 if (hasCycle(graph, color, states))37 return false;38 39 return true;40 }41 42 private:43 bool hasCycle(const vector<unordered_set<int>>& graph, int u,44 vector<State>& states) {45 if (states[u] == State::kVisiting)46 return true;47 if (states[u] == State::kVisited)48 return false;49 states[u] = State::kVisiting;50 for (const int v : graph[u])51 if (hasCycle(graph, v, states))52 return true;53 states[u] = State::kVisited;54 return false;55 }56};57