diff --git a/content/Leetcode Questions/Pyramid Transition Matrix.md b/content/Leetcode Questions/Pyramid Transition Matrix.md new file mode 100644 index 0000000..764b59c --- /dev/null +++ b/content/Leetcode Questions/Pyramid Transition Matrix.md @@ -0,0 +1,553 @@ +--- +date: 2025-12-31 +tags: + - DFS + - Search + - Cache +--- +[Leetcode Question Link](https://leetcode.com/problems/pyramid-transition-matrix/) + +# Analyze + +## Basic Thought + +For each pyramid block, the possible color (represented by one single character) is limited to following: + +``` +color = A, B, C, D, E, F +``` + +The intuitive is to use #Search to **iterate through the solution space** *(all possible value of the elements in pyramid)* to find the final answer. + +## Searching + +### Store Current Search State + +The the image shows below, we store the pyramid info info an 2D `char` array: + +![[251231_store_search_info.png]] + +And define meaning of the value in the elements as follow: + +| Value | Description | +| ------- | ---------------- | +| `0` | Not yet searched | +| `[A-F]` | Searching | +| `1` | Searched | + +### Search Direction + +We search **from right to left, from bottom to top**. More concretely, consider current searching position is `[curR][curC]`, then next search position could be calculated by code below: + +```python +def pos_forward(curR, curC): + if(curC > 0): + --curC # one step left + else: + --curR # search the layer above + curC = curR # start from right-most element +``` + +> [!note] +> +> Please note that all Python code in this post is intended solely to illustrate the logic and should be regarded as pseudocode. +> +> For runnable C++ code, checkout [[#Code Implementation]] sector. + +![[251231_search_direction.png]] + +### Search Implementation + +I decided to use a **non-recursive way** to implement DFS search in the solution space. + +The search strategy could be explained by the code below: + +```python +def _search(): + # global variables + global curR + global curC + + # if already found valid answer, or search already finished + # return directly + if found or finished: + return + + # search for this position is finished + if currChar == '1': + + # if this is the search starting point + # then it means the whole solution space has been searched + if [curR, curC] == [bottom_size - 1, bottom_size - 1]: + finished = True + return + + # else, we go one step backward. + # + # setting current position value to '0' is necessary, + # since if not doing so, next time we search this position, + # program will directly skip searching and go backward() + currChar == '0' + pos_backward() + return + + # at here, the search of current position must NOT finished + currChar = next_possible_char_for_this_pos() + + # this is the last position to search, and we found a valid color + if currChar != '1' and [curR, curC] == [0, 0]: + found = True + return + + pos_forward() + + +def search() -> bool: + while (not finished) and (not found): + _search() + + return found +``` + +In code above: + +- `pos_forward() / pos_backward()` modify `curR, curC` to point to next / previous search position +- `next_possible_char_for_this_pos()` will return next valid color character for current position based on allowed patterns and values in `[curR + 1][curC]` and `[curR + 1][curC + 1]` + +```python +def next_possible_char_for_this_pos(): + if curChar == '0': + curChar = 'A' - 1 + + curChar++ + + while curChar <= 'F' + is_valid = check_pattern( + top=curChar, + bottom_left=pyramid[curR + 1][curC], + bottom_right=pyramid[curR + 1][curC + 1], + ) + if is_valid: + break + + if curChar > 'F': + curChar = '1' +``` + +## Caching + +Purely solution space searching **without any cache** could **not pass all the testcase** *(due to `TLE`)*. + +Therefore, we need to exploit the info produced during searching to **cache some impossible answer of sub-question** and use such cache in proper time. + +### Set Cache + +We could trigger set cache when **searching position change to the lower layer**. + +Let's say, the position row index *(or we could say, layer index)* from `curR = 1` to `curR = 2`, then at this point, we could be sure the sub question using bottom sequence as current layer 2 is impossible. + +![[251231_no_solution.png]] + +This is because, if such sub question `B, D, C` have solution, the search position will finally go to the `curR = 0, curC = 0` and set `found = 1`, thus, the search is finished, and we found a valid solution for original question, and such solution use `B, D, C` as layer 2 elements. + +> [!note] +> +> Here, sub question of a sequence means that: "If we could find a possible pyramid if the bottom is such sequence". +> +> For example, sub question using `B, D, C` as sequence means if we could find a valid pyramid that using `B, D, C` as the pyramid bottom. + +### Use Cache + +Based on analysis above, it's easy to know we could use cache when **searching position changes to higher layer**. + +![[251231_use_cache.png]] + +As the image above, when we goes from `[2][0]` to `[1][1]`, before start searching, we first check if the sub questions of layer 2: `B, D, C` is in the cache. + +If cache hit, it means such **sub question has no solution** and we should **not wasting time searching further** anymore. Instead, we directly go back to `[2][0]` again, set it to next possible value *(for example from `B` to `C` in the image)* then keep searching. + +> [!note] +> +> We **only need to cache the invalid sub questions**, thus, the cache could be stored in a set, e.g. `std::unurdered_set cache`. As long as a string sequence is in the cache *(could be checked using `cache.contains(str)`)*, we can sure it doesn't have solution. + +> [!note] +> +> It's easy to proof **we don't need to cache the "valid" solution** of any sub question. Reusing example above, if the `B, D, C` sub sequence is valid as a pyramid bottom, then we will not even have a chance to cache it since the search procedure will reach the top of pyramid and declare `found = true`. +> +> In other word, if any sub question is valid in our definition, it must also indicate the original question solution is also being found. + +# Code Implementation + +```cpp +#include +#include +#include +#include +#include +#include +#include +#include + +using std::cout, std::endl; +using std::format; +using std::vector, std::string; + +bool debug = false; + +/** + * Data structure to store pattern in question + * + * Init: + * - Use 3-char string to init (based on questoni definition) + * - Use three different char parameter to init + * + * Method: + * - Equal comparator + * - hash() function + */ +struct Pattern +{ + char top; + char left; + char right; + + Pattern(const string &data) + { + top = data[2]; + left = data[0]; + right = data[1]; + } + + Pattern(char top, char left, char right) + : top(top), left(left), right(right) {} + + bool operator==(const Pattern &other) const + { + return top == other.top && left == other.left && right == other.right; + } + + size_t hash() const + { + return std::hash()(top) + std::hash()(left) + + std::hash()(right); + } +}; + +struct PatternHash +{ + size_t operator()(const Pattern &p) const { return p.hash(); } +}; + +class PatternManager +{ +private: + std::unordered_set mPatterns; + bool mPairs[6][6]; + +public: + PatternManager() + { + clear(); + } + + void add(const Pattern &p) + { + mPatterns.insert(p); + mPairs[p.left - 'A'][p.right - 'A'] = 1; + } + + bool exists(const Pattern &p) + { + if (!mPairs[p.left - 'A'][p.right - 'A']) + { + return false; + } + return mPatterns.find(p) != mPatterns.end(); + } + + void clear() + { + mPatterns.clear(); + for (int i = 0; i < 6; ++i) + { + for (int j = 0; j < 6; ++j) + { + mPairs[i][j] = 0; + } + } + } +}; + +// global variables +// statistics +unsigned bottomSize = 0; +string bottomString; +char pyramid[6][6]; // 0: not searched, A-F: searching, 1: finished +PatternManager pMgr; +// search temp +unsigned curR, curC; +bool found, finished; + +class AnswerCache +{ +private: + std::unordered_map mAllowedBottomcache; + + string wholeRowToString(unsigned rowIdx) + { + string s = ""; + for (int i = 0; i <= rowIdx; ++i) + { + s.push_back(pyramid[rowIdx][i]); + } + + return s; + } + +public: + AnswerCache() {} + + void setCache() + { + mAllowedBottomcache[wholeRowToString(curR)] = false; + } + + // false: not in cache, true: hit + int getCache(int rowIdx) + { + string rowStr = wholeRowToString(rowIdx); + return mAllowedBottomcache.contains(rowStr); + } + + void clear() + { + mAllowedBottomcache.clear(); + } +}; + +AnswerCache ansCache; + +class Initializer +{ +public: + // init variables and clear mMgr + void initVariables() + { + // init temp + curR = bottomSize - 2; + curC = bottomSize - 2; + found = 0; + finished = 0; + + // clear manager + pMgr.clear(); + ansCache.clear(); + + // clear answer cache + + // init pyramid + for (int i = 0; i < 6; ++i) + { + for (int j = 0; j < 6; ++j) + { + pyramid[i][j] = '0'; + } + } + } + + // init bottomString and the pyramid array + void initPyramidBottom(const string &data) + { + bottomString = data; + + for (int i = 0; i < bottomSize; ++i) + { + pyramid[bottomSize - 1][i] = data[i]; + } + } + + // fill data to mMgr + void initPattern(const vector &allowed) + { + for (const auto &s : allowed) + { + pMgr.add(Pattern(s)); + } + } +}; + +class Searcher +{ +private: + bool deltaSearchpointer(bool forward) + { + // forward + if (forward) + { + if (curR <= 0 && curC <= 0) + { + return false; + } + + if (curC > 0) + { + --curC; + } + else + { + --curR; + curC = curR; + } + return true; + } + // backward + else + { + if (curC >= bottomSize - 2 && curR >= bottomSize - 2) + { + return false; + } + + if (curC < curR) + { + ++curC; + } + else + { + ++curR; + curC = 0; + } + return true; + } + } + + char &curChar() { return pyramid[curR][curC]; } + + char &leftChar() { return pyramid[curR + 1][curC]; } + + char &rightChar() { return pyramid[curR + 1][curC + 1]; } + + bool atTop() { return curR == curC && curC == 0; } + + bool curValid() + { + return pMgr.exists(Pattern(curChar(), leftChar(), rightChar())); + } + + void setToNextPossibleChar() + { + // search end + if (curChar() == '1') + { + return; + } + + // search not begin + if (curChar() == '0') + { + curChar() = 'A'; + if (curValid()) + { + return; + } + } + + ++curChar(); + + while (curChar() <= 'F' && !curValid()) + { + ++curChar(); + } + + if (curChar() > 'F') + { + curChar() = '1'; + } + } + + void _search() + { + + // already found answer + if (found || finished) + { + return; + } + + // try use cache to check if we could skip current layer + // before we are about to start a new upper layer + if (curC == curR && curChar() == '0') + { + if (ansCache.getCache(curR + 1)) + { + deltaSearchpointer(0); + return; + } + } + + setToNextPossibleChar(); + + bool isDelta; + + // this position finished + if (curChar() == '1') + { + isDelta = deltaSearchpointer(0); + + // finished + if (!isDelta) + { + finished = 1; + } + + // back to lower layer + if (curC == 0) + { + // remember this layer of pattern doesn't work + ansCache.setCache(); + } + return; + } + + // this position not finish searching + isDelta = deltaSearchpointer(1); + if (!isDelta) + { + found = 1; + } + else + { + curChar() = '0'; + } + return; + } + +public: + void search() + { + while (!found && !finished) + { + _search(); + } + } +}; + +class Solution +{ +public: + bool pyramidTransition(string bottom, vector &allowed) + { + // initialization + bottomSize = bottom.size(); + auto initer = Initializer(); + initer.initVariables(); + initer.initPyramidBottom(bottom); + initer.initPattern(allowed); + + // search the answer + auto searcher = Searcher(); + searcher.search(); + return found; + } +}; +``` \ No newline at end of file diff --git a/content/Leetcode Questions/assets/251231_no_solution.png b/content/Leetcode Questions/assets/251231_no_solution.png new file mode 100644 index 0000000..8420042 --- /dev/null +++ b/content/Leetcode Questions/assets/251231_no_solution.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94efba5b9165f439ba90c93710d06dccd7be652455b3e782a7fb8b6b087ceb0a +size 40200 diff --git a/content/Leetcode Questions/assets/251231_search_direction.png b/content/Leetcode Questions/assets/251231_search_direction.png new file mode 100644 index 0000000..e301e81 --- /dev/null +++ b/content/Leetcode Questions/assets/251231_search_direction.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e59a7dad9982e007ade67a5ceac828846c303b5176f4b6e17a31cf0c14f8766 +size 65220 diff --git a/content/Leetcode Questions/assets/251231_store_search_info.png b/content/Leetcode Questions/assets/251231_store_search_info.png new file mode 100644 index 0000000..7d09d22 --- /dev/null +++ b/content/Leetcode Questions/assets/251231_store_search_info.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9441a34b10f4de774b2f111e9fc5c61f96beac891dde7651f627b5cf54da5a1 +size 36722 diff --git a/content/Leetcode Questions/assets/251231_use_cache.png b/content/Leetcode Questions/assets/251231_use_cache.png new file mode 100644 index 0000000..413cd0e --- /dev/null +++ b/content/Leetcode Questions/assets/251231_use_cache.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10d219a7fc0839a4b35c3747d7bcf885cd0a834785752302413815ad96d1f1ad +size 57236 diff --git a/test.cpp b/test.cpp index b6bc5bf..9486f01 100644 --- a/test.cpp +++ b/test.cpp @@ -111,7 +111,9 @@ class AnswerCache { private: std::unordered_map mAllowedBottomcache; + unsigned long long cacheHit, cacheWrite, cacheRead; +private: string wholeRowToString(unsigned rowIdx) { string s = ""; @@ -134,13 +136,22 @@ public: // false: not in cache, true: hit int getCache(int rowIdx) { + ++cacheRead; string rowStr = wholeRowToString(rowIdx); return mAllowedBottomcache.contains(rowStr); } + void showCacheStatus() + { + cout << format("cache R/W: {}/{}, cache hit:{}\n", cacheRead, cacheWrite, cacheHit); + } + void clear() { mAllowedBottomcache.clear(); + cacheHit = 0; + cacheRead = 0; + cacheWrite = 0; } }; @@ -160,9 +171,9 @@ public: // clear manager pMgr.clear(); - ansCache.clear(); // clear answer cache + ansCache.clear(); // init pyramid for (int i = 0; i < 6; ++i) @@ -255,6 +266,8 @@ private: void setToNextPossibleChar() { + bool firstMove = (curChar() == '0'); + // search end if (curChar() == '1') { @@ -286,10 +299,15 @@ private: void _search() { + if (debug) + { + cout << "enter _search()" << endl; + } // already found answer if (found || finished) { + cout << "found or finished" << endl; return; } @@ -347,6 +365,10 @@ public: while (!found && !finished) { _search(); + if (debug) + { + cout << format("found={}, finished={}\n", found, finished); + } } } }; @@ -366,6 +388,7 @@ public: // search the answer auto searcher = Searcher(); searcher.search(); + ansCache.showCacheStatus(); return found; } }; \ No newline at end of file