Depth-first search algorithm questions and analysis

Depth-first search algorithm questions and analysis

The topic is as follows

Child A is playing a messaging game with ta’s friends. The rules of the game are as follows:

There are n players, all of which are numbered from 0 to n-1, among which the number of child A is 0.
Each player has a fixed number of other players (or there may not be) who can transmit information. The information transmission relationship is one-way (for example, A can transmit information to B, but B cannot transmit information to A).
Each round of information must be transmitted to another person, and the information can be repeated through the same person.
Given the total number of players n, and press [player number, corresponding passable player number] relationship composed of a two-dimensional array relation. The return information is the number of plans passed from small A (number 0) to the small partner number n-1 through k rounds; if it cannot be reached, return 0.

Example 1:

Input: n = 5, relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4] ], k = 3

Output: 3

Explanation: The information starts at number 0 of small A, passes through 3 rounds, and reaches number 4. There are 3 schemes, namely 0->2->0->4, 0->2->1->4, 0->2->3->4.

Example 2:

Input: n = 3, relation = [[0,2],[2,1]], k = 2

Output: 0

Explanation: The information cannot be passed from Small A to No. 2 in 2 rounds

limit:

2 <= n <= 10
1 <= k <= 5
1 <= relation.length <= 90, 且 relation[i].length == 2
0 <= relation[i][0],relation[i][1] < n 且 relation[i][0] != relation[i][1]

The solution is as follows

k represents the number of steps, and each step is k-1. When k=0, stop, if it happens to be n-1, then res++.

class Solution {
    
    
    int res=0;
    public int numWays(int n, int[][] relation, int k){
    
    
        dfs(n,relation,k,0);
        return res;
    }
    
    public void dfs(int n,int[][] r,int k,int curr){
    
    
        if (k==0){
    
    
            if (curr==n-1) res++;
        }
        for (int i=0;i<r.length;i++){
    
    
            if (curr==r[i][0] && k>0){
    
    
                dfs(n,r,k-1,r[i][1]);
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43372169/article/details/109956092