小米Git

来源:互联网 发布:酷家乐绘图软件 编辑:程序博客网 时间:2024/06/10 05:14

git是一种分布式代码管理工具,git通过树的形式记录文件的更改历史,比如: base’<–base<–A<–A’ ^ | — B<–B’ 小米工程师常常需要寻找两个分支最近的分割点,即base.假设git 树是多叉树,请实现一个算法,计算git树上任意两点的最近分割点。 (假设git树节点数为n,用邻接矩阵的形式表示git树:字符串数组matrix包含n个字符串,每个字符串由字符’0’或’1’组成,长度为n。matrix[i][j]==’1’当且仅当git树种第i个和第j个节点有连接。节点0为git树的根节点。)

import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Queue;public class Solution {    /**     * 返回git树上两点的最近分割点     *      * @param matrix     *            接邻矩阵,表示git树,matrix[i][j] == '1'     *            当且仅当git树中第i个和第j个节点有连接,节点0为git树的跟节点     * @param indexA     *            节点A的index     * @param indexB     *            节点B的index     * @return 整型     */    public int getSplitNode(String[] matrix, int indexA, int indexB) {        if (matrix == null) {            return 0;        }        List<Integer> pathA = BFS(matrix, matrix.length, indexA);        List<Integer> pathB = BFS(matrix, matrix.length, indexB);        if (pathA != null && pathB != null) {            for (int i = 0, lenght1 = pathA.size(); i < lenght1; i++) {                for (int j = 0, lenght2 = pathB.size(); j < lenght2; j++) {                    if (pathA.get(i) == pathB.get(j)) {                        return pathA.get(i);                    }                }            }        }        return 0;    }    /**     * 节点到root的路径遍历     *      * @param matrix     * @param index     * @return     */    public List<Integer> BFS(String[] matrix, int length, int index) {        Queue<List<Integer>> queue = new ArrayDeque<List<Integer>>();        List<Integer> path = Arrays.asList(new Integer[] { index });        queue.add(path);        while (!queue.isEmpty()) {            List<Integer> cur = queue.poll();            int curIndex = cur.get(cur.size() - 1);            if (curIndex == 0) {                return cur;            }            for (int i = 0; i < length; i++) {                if (curIndex != i && matrix[curIndex].charAt(i) == '1'                        && !cur.contains(i)) {                    List<Integer> tmp = clone(cur);                    tmp.add(i);                    queue.add(tmp);                }            }        }        return null;    }    public List<Integer> clone(List<Integer> src) {        List<Integer> dest = new ArrayList<Integer>();        for (Integer i : src) {            dest.add(i);        }        return dest;    }}
0 0
原创粉丝点击