- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 39 lines of C++ from the credited upstream file 2912-2.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int numberOfWays(int n, int m, int k, vector<int>& source,4 vector<int>& dest) {5 constexpr int kMod = 1'000'000'007;6 7 int ans = source[0] == dest[0] && source[1] == dest[1];8 9 int row = source[0] == dest[0] && source[1] != dest[1];10 11 int col = source[0] != dest[0] && source[1] == dest[1];12 13 int others = source[0] != dest[0] && source[1] != dest[1];14 15 for (int i = 0; i < k; ++i) {16 const int nextAns = (row + col) % kMod;17 const int nextRow = static_cast<int>((ans * (m - 1L) + 18 row * (m - 2L) + 19 others) %20 kMod);21 const int nextCol = static_cast<int>((ans * (n - 1L) + 22 col * (n - 2L) + 23 others) %24 kMod);25 const int nextOthers =26 static_cast<int>((row * (n - 1L) + 27 col * (m - 1L) + 28 others * (m + n - 1 - 3L)) % 29 kMod);30 ans = nextAns;31 row = nextRow;32 col = nextCol;33 others = nextOthers;34 }35 36 return ans;37 }38};39