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);            
            }
        }
    }
};