题解 | #小米Git#

小米Git

https://www.nowcoder.com/practice/4fcd94851d9142458329fd1d3e5802a8

import java.util.*;


public class Solution {
    
    public void dfs(int node, int father, int dep, int[] path, int[] depth,String[] mat) {
        depth[node] = dep;
        path[node] = father;
        for (int i = 0; i < mat.length; i++) {
            if (i != father && mat[node].charAt(i)=='1') {
                dfs(i,node,dep+1,path,depth,mat);
            }
        }
    }
    public int Git(String[] matrix, int indexA, int indexB) {
        int n  = matrix.length;
        int[] depth = new int[n];
        int[] father = new int[n];
        father[0] = -1;
        dfs(0,-1,0,father,depth,matrix);
        while (depth[indexA] > depth[indexB]) {
            indexA = father[indexA];
        }
        while (depth[indexB] > depth[indexA]) {
            indexB = father[indexB];
        }
        while (indexA != indexB) {
            indexA = father[indexA];
            indexB = father[indexB];
        }
        return indexA;
    }
}

全部评论
效率有点低啊兄弟
点赞
送花
回复
分享
发布于 2022-08-11 14:59
copy的吧
点赞
送花
回复
分享
发布于 2022-08-11 14:59
秋招专场
校招火热招聘中
官网直投

相关推荐

3 收藏 评论
分享
牛客网
牛客企业服务