Leetcode LCP-07
LCP 07. 传递信息
看用例就可以知道这是一个图,[u , v]
用dfs深度优先来一步一步搜寻到末端
public int numWays(int n, int[][] relations, int k) {
int cnt = 0;
boolean[][] isVisited = new boolean[n][n];//判断是否经过
for (int[] relation : relations) {
isVisited[relation[0]][relation[1]] = true;
}
return dfs(0 , isVisited , k);
}
public int dfs(int n , boolean[][] isVisited , int k){
if (k == 0){
return isVisited.length - 1 == n ? 1 : 0;
}
int cnt = 0 ;
for (int i = 0; i < isVisited[n].length; i++) {
if (isVisited[n][i]){//是则加1
cnt += dfs(i , isVisited , k - 1);//递归
}
}
return cnt;
}