Created
October 1, 2018 00:00
-
-
Save willwangcc/820731c657a48196a3868988acd4d3f6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Time: O(n^3) where n is the number of nodes in the graph. There are O(N^2) states, and each state has an outdegree of NN, as there are at most NN different moves. | |
# Space: O(n^2) | |
class Solution: | |
def catMouseGame(self, graph): | |
""" | |
:type graph: List[List[int]] | |
:rtype: int | |
""" | |
self.graph = graph | |
self.memo = {} | |
return self.move(2, 1, True) | |
def move(self, cat, mouse, m_turn): | |
key = (cat, mouse, m_turn) | |
if key in self.memo: | |
return self.memo[key] | |
self.memo[key] = 0 | |
if m_turn: | |
return self.mouse_play(key, cat, mouse, m_turn) | |
else: | |
return self.cat_play(key, cat, mouse, m_turn) | |
def mouse_play(self, key, cat, turn, m_turn): | |
# base case | |
for nxt in self.graph[turn]: | |
if nxt == 0: | |
self.memo[key] = 1 | |
return 1 | |
res = 2 | |
for nxt in self.graph[turn]: | |
if nxt == cat: | |
continue | |
tmp = self.move(cat, nxt, False) | |
if tmp == 1: | |
res = 1 | |
break | |
if tmp == 0: | |
res = 0 | |
self.memo[key] = res | |
return res | |
def cat_play(self, key, turn, mouse, m_turn): | |
# base case | |
for nxt in self.graph[turn]: | |
if nxt == mouse: | |
self.memo[key] = 2 | |
return 2 | |
res = 1 | |
for nxt in self.graph[turn]: | |
if nxt ==0: | |
continue | |
tmp = self.move(nxt, mouse, True) | |
if tmp == 2: | |
res = 2 | |
break | |
if tmp == 0: | |
res = 0 | |
self.memo[key] = res | |
return res | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment