913.Cat and Mouse
示例:
- 输入:[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
- 输出:0
- 解释:- 提示:
3 <= graph.length <= 200
保证 graph[1] 非空。
保证 graph[2] 包含非零元素。Last updated
示例:
- 输入:[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
- 输出:0
- 解释:- 提示:
3 <= graph.length <= 200
保证 graph[1] 非空。
保证 graph[2] 包含非零元素。Last updated
class Solution {
public:
vector<vector<vector<int>>>f;
int catMouseGame(vector<vector<int>>& graph) {
int size=graph.size();
f = vector<vector<vector<int>>>(size*2, vector<vector<int>>(size, vector<int>(size,-1)));
return result(graph,0,1,2);
}
private:
int result(const vector<vector<int>>& graph, int t,int x,int y)
{
if(t == graph.size() *2)
return 0;
if(x == y)
return f[t][x][y]=2;
if(x == 0)
return f[t][x][y]=1;
if(f[t][x][y] !=-1)
return f[t][x][y];
int who = t % 2;
bool flag;
if(!who)
{
flag=true;
for(int i=0;i<graph[x].size();i++)
{
int nx= result(graph,t+1,graph[x][i],y);
if(nx == 1)
return f[t][x][y]=1;
if(nx !=2)
flag=false;
}
if (flag)
return f[t][x][y]=2;
else
return f[t][x][y]=0;
}
else
{
flag = true;
for(int i=0;i<graph[y].size();i++)
{
if(graph[y][i] ==0) continue;
int ny = result(graph,t+1,x,graph[y][i]);
if(ny==2)
return f[t][x][y]=2;
if(ny!=1)
flag = false;
}
if(flag)
return f[t][x][y]=1;
else
return f[t][x][y]=0;
}
}
};