Approach
Breadth-first search
For Cat and Mouse, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 59 lines of C++ from the credited upstream file 913.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 { kDraw, kMouseWin, kCatWin };2 3class Solution {4 public:5 int catMouseGame(vector<vector<int>>& graph) {6 const int n = graph.size();7 8 9 vector<vector<vector<State>>> states(10 n, vector<vector<State>>(n, vector<State>(2)));11 vector<vector<vector<int>>> outDegree(12 n, vector<vector<int>>(n, vector<int>(2)));13 queue<tuple<int, int, int, State>> q; 14 15 for (int cat = 0; cat < n; ++cat)16 for (int mouse = 0; mouse < n; ++mouse) {17 outDegree[cat][mouse][0] = graph[mouse].size();18 outDegree[cat][mouse][1] =19 graph[cat].size() - ranges::count(graph[cat], 0);20 }21 22 23 for (int cat = 1; cat < n; ++cat)24 for (int move = 0; move < 2; ++move) {25 26 states[cat][0][move] = State::kMouseWin;27 q.emplace(cat, 0, move, State::kMouseWin);28 29 states[cat][cat][move] = State::kCatWin;30 q.emplace(cat, cat, move, State::kCatWin);31 }32 33 while (!q.empty()) {34 const auto [cat, mouse, move, state] = q.front();35 q.pop();36 if (cat == 2 && mouse == 1 && move == 0)37 return static_cast<int>(state);38 const int prevMove = move ^ 1;39 for (const int prev : graph[prevMove ? cat : mouse]) {40 const int prevCat = prevMove ? prev : cat;41 if (prevCat == 0) 42 continue;43 const int prevMouse = prevMove ? mouse : prev;44 45 if (states[prevCat][prevMouse][prevMove] != State::kDraw)46 continue;47 if (prevMove == 0 && state == State::kMouseWin ||48 prevMove == 1 && state == State::kCatWin ||49 --outDegree[prevCat][prevMouse][prevMove] == 0) {50 states[prevCat][prevMouse][prevMove] = state;51 q.emplace(prevCat, prevMouse, prevMove, state);52 }53 }54 }55 56 return static_cast<int>(states[2][1][0]);57 }58};59