2021-07-19 16:03

# 如何使用递归解决血缘关系判断？

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 3条回答默认 最新

• HHeyJ 2021-07-19 17:04
已采纳

如果不考虑兄弟姐妹的话如下：
找到A的父母2人，祖父母4人(父母的父母)，曾祖父母8人(父母的父母的父母)
同理找到B的父母、祖父母、曾祖父母

判断他们每一代是否有重复即可，流程上能够从父母辈开始判断有重复即结束，是否向上继续追溯祖父母，同理无重复再追溯曾祖父母

点赞 评论
• 木人_朽月 2021-07-19 17:18
``````
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {
Pig p15 = new Pig(15,null,null);
Pig p14 = new Pig(14,null,null);
Pig p13 = new Pig(13,null,null);
Pig p12 = new Pig(12,null,null);
Pig p11 = new Pig(11,null,null);
Pig p10 = new Pig(10,null,null);
Pig p9 = new Pig(9,null,null);
Pig p8 = new Pig(8,null,null);
Pig p7 = new Pig(7,p14,p15);
Pig p6 = new Pig(6,p12,p13);
Pig p5 = new Pig(5,p10,p11);
Pig p4 = new Pig(4,p8,p9);
Pig p3 = new Pig(3,p6,p7);
Pig p2 = new Pig(2,p4,p5);
Pig p1 = new Pig(1,p2,p3);
Pig p16 = new Pig(1,p4,p5);

System.out.println(find(p1,p16,4));
}

//  俺是pigA，她是pigB，俺俩配种
public static boolean find(Pig pigA,Pig pigB,int generation){
//  俺的4代祖宗
List<Pig> aAncestry = new ArrayList<Pig>();
//  她的4代祖宗
List<Pig> bAncestry = new ArrayList<Pig>();

//  添加俺爸和俺爸的祖宗
if(pigA.father != null)
//  添加俺妈和俺妈的祖宗
if(pigA.mother != null)

//  添加她爸和她爸的祖宗
if(pigB.father != null)
//  添加她妈和她妈的祖宗
if(pigB.mother != null)

//  祖宗对比
for(Pig pigAancestry: aAncestry){
for(Pig pigBancestry: bAncestry){
//  同一个祖宗
if(pigAancestry.getSelfId() == pigBancestry.getSelfId()){
System.out.println("俺祖宗："+pigAancestry.toString());
System.out.println("她祖宗："+pigBancestry.toString());
return true;
}
}
}

return false;
}

public static void addAncerstry(List<Pig> ancestry,Pig pig,int generation){
if(generation == 1)
return;
if(pig.father != null)
if(pig.mother != null)
}

static class Pig{
//  猪的标识
private int selfId;
//  猪它爸
private Pig father;
//  猪它妈
private Pig mother;

public Pig(int selfId, Pig father, Pig mother) {
this.selfId = selfId;
this.father = father;
this.mother = mother;
}

@Override
public String toString() {
return "Pig{" +
"selfId=" + selfId +
", father=" + father +
", mother=" + mother +
'}';
}

public int getSelfId() {
return selfId;
}

public void setSelfId(int selfId) {
this.selfId = selfId;
}

public Pig getFather() {
return father;
}

public void setFather(Pig father) {
this.father = father;
}

public Pig getMother() {
return mother;
}

public void setMother(Pig mother) {
this.mother = mother;
}
}
}

``````

从下往上，看，1的爸妈是2和3，2的爸妈是4和5

点赞 1 评论
• wenmh 2021-07-19 16:14

我现在可以通过猪的特定标识在数据库表中找到它的父母，后面应该要如何去实现这个四代比对过程呢？

点赞 评论