题解 | #小米Git#

小米Git

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

class Solution
{
    //树是特殊的图  采用递归思想 找子孙节点   
    // 参考 https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/


private:
    int shared_a, shared_b;//保存目标值
    bool flag = 0;//判断两个节点是否在树同侧
public:
    int Search(vector<string>& a, int j)
    {
        int res = -1, count = 0;//count 判断是否同侧
        if (j == shared_a || j == shared_b)count++, res = j;
        if (flag)return -1; //剪枝
        for (int i = 0; i < a[j].size(); ++i)
        {
            if (a[j][i] == '1')
            {
                if (i == shared_a || i == shared_b)
                {
                    res = i, count += 1;
                    continue;
                }
                if (i < a.size())
                {
                    a[i][j] = '0';//去环 
                    int t = Search(a, i);
                    if (t != -1)
                    {
                        res = t;
                        count += 1;
                    }
                }
            }
        }
        if (count > 1) {
            flag = true;
            return j;
        }
        return res;
    }
    int Git(vector<string>& matrix, int versionA, int versionB)
    {
        shared_a = versionA, shared_b = versionB;
        if (matrix.size() == 1)
        {
            return 0;
        }
        else
        {
            if (shared_a == shared_b)return shared_a;
            else {
                return Search(matrix, 0);            
            }
        }
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
M_bao:换个排版吧哥们,看着费劲
点赞 评论 收藏
分享
蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务