Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool canMouseWin(vector<string>& grid, int catJump, int mouseJump) {4 const int m = grid.size();5 const int n = grid[0].size();6 int nFloors = 0;7 int cat; 8 int mouse; 9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j) {12 if (grid[i][j] != '#')13 ++nFloors;14 if (grid[i][j] == 'C')15 cat = hash(i, j, n);16 else if (grid[i][j] == 'M')17 mouse = hash(i, j, n);18 }19 20 vector<vector<vector<int>>> mem(21 m * n, vector<vector<int>>(m * n, vector<int>(nFloors * 2, -1)));22 return canMouseWin(grid, cat, mouse, 0, catJump, mouseJump, m, n, nFloors,23 mem);24 }25 26 private:27 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};28 29 30 31 bool canMouseWin(const vector<string>& grid, int cat, int mouse, int turn,32 const int& catJump, const int& mouseJump, const int& m,33 const int& n, const int& nFloors,34 vector<vector<vector<int>>>& mem) {35 36 if (turn == nFloors * 2)37 return false;38 if (mem[cat][mouse][turn] != -1)39 return mem[cat][mouse][turn];40 41 if (turn % 2 == 0) {42 43 const int i = mouse / n;44 const int j = mouse % n;45 for (const auto& [dx, dy] : kDirs) {46 for (int jump = 0; jump <= mouseJump; ++jump) {47 const int x = i + dx * jump;48 const int y = j + dy * jump;49 if (x < 0 || x == m || y < 0 || y == n)50 break;51 if (grid[x][y] == '#')52 break;53 54 if (grid[x][y] == 'F')55 return mem[cat][mouse][turn] = true;56 if (canMouseWin(grid, cat, hash(x, y, n), turn + 1, catJump,57 mouseJump, m, n, nFloors, mem))58 return mem[cat][mouse][turn] = true;59 }60 }61 62 return mem[cat][mouse][turn] = false;63 } else {64 65 const int i = cat / n;66 const int j = cat % n;67 for (const auto& [dx, dy] : kDirs) {68 for (int jump = 0; jump <= catJump; ++jump) {69 const int x = i + dx * jump;70 const int y = j + dy * jump;71 if (x < 0 || x == m || y < 0 || y == n)72 break;73 if (grid[x][y] == '#')74 break;75 76 if (grid[x][y] == 'F')77 return mem[cat][mouse][turn] = false;78 const int nextCat = hash(x, y, n);79 80 if (nextCat == mouse)81 return mem[cat][mouse][turn] = false;82 if (!canMouseWin(grid, nextCat, mouse, turn + 1, catJump, mouseJump,83 m, n, nFloors, mem))84 return mem[cat][mouse][turn] = false;85 }86 }87 88 return mem[cat][mouse][turn] = true;89 }90 }91 92 int hash(int i, int j, int n) {93 return i * n + j;94 }95};96