题解 | #小米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);            
            }
        }
    }
};

全部评论

相关推荐

03-10 14:19
已编辑
重庆邮电大学 前端工程师
球Offer上岸:测试也难求一面 逆天
点赞 评论 收藏
分享
大清早迷迷糊糊被闹钟叫醒,坐在电脑面前开始答题,硬生生坐了2小时,要是不进面,我都无颜面对我的屁股
在看数据的傻狍子很忙碌:26届还好啦。我昨晚还要跟mt值班降级熔断的测试 , 回来做一下上周的美团笔试 , 做完已经快三点了。只a出1.25。而且手机还断网了4次五六秒,已经心碎了。
投递美团等公司10个岗位 > 美团求职进展汇总
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务