[LeetCode] Pyramid Transition Matrix

756. Pyramid Transition Matrix

You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.

To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.

  • For example, “ABC” represents a triangular pattern with a ‘C’ block stacked on top of an ‘A’ (left) and ‘B’ (right) block. Note that this is different from “BAC” where ‘B’ is on the left bottom and ‘A’ is on the right bottom.

You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.

Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
vector<char> mp[26][26];
unordered_set<string> vis;

vector<string> combs(string& now) {
vector<string> res{""};
for(int i = 0; i < now.length() - 1; i++) {
vector<string> nxt;
for(auto& r : res) {
if(mp[now[i] - 'A'][now[i + 1] - 'A'].empty()) return {};
for(auto& ch : mp[now[i] - 'A'][now[i + 1] - 'A'])
nxt.push_back(r + ch);
}
swap(res, nxt);
}
return res;
}
bool helper(string& s) {
if(s.length() == 1) return true;
if(vis.count(s)) return false;
vis.insert(s);
for(auto& n : combs(s)) {
if(helper(n))
return true;
}
return false;
}
public:
bool pyramidTransition(string bottom, vector<string>& allowed) {
for(auto& a : allowed) {
mp[a[0] - 'A'][a[1] - 'A'].push_back(a[2]);
}
return helper(bottom);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/18/PS/LeetCode/pyramid-transition-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.