Lab1实验过程记录
3.Social Network
第三题要求实现FriendshipGraph和Person类,来对人际关系进行简单的图表示,并可计算最短关系路径长度。使用了广度优先搜索算法。今后的扩展应该会用到集合论与图论的相关知识。
实现的Person类由于现阶段并没有做任务要求,只包含了一个记录名字的string成员,以及一个返回名字的getname()方法。另外还要求使用JUnit编写FriendshipGraphTest()测试,实现也较为简单,在此略过。
重点介绍FriendshipGraph类实现。
ArrayList<Person> personList = new ArrayList<Person>();
ArrayList<ArrayList<Integer>> relationNet = new ArrayList<ArrayList<Integer>>();
类中包含了以上两个变长数组成员。personList用于存储图中所有的Person实例(并对应一个下标)。relationNet为二维变长数组,用于存储任意两个Person的单向关系,其中存储1表示存在单向关系,存储-1表示不存在单向关系。
类中包含以下要求实现的方法:
addVertex():添加顶点方法。先检测输入顶点是否已经包含在图中。若输入合法,则将将其添加进personList中(则其下标为数组尾部),并更新relationNet中的相应内容,每个已有的list在末尾添加一个-1,再新建一个list存储对应顶点数量的-1。注意数组的最后一个元素赋值为1,即默认新的顶点初始时不与其他任何顶点存在关系,且所有Person到自己存在单向关系。
AddEdge():添加边方法。检测输入顶点是否均包含在图中且不相等,若输入合法,更新relationNet中的相应内容,更新单向关系为1。按照要求,新添加的关系应为单向,实现有向图以便后续方法扩展。
getDistance():计算最短路径方法。使用广度优先遍历的算法思路实现,使用一位数组存储起始顶点到其余各顶点的距离,初始为-1(到自身初始为0)。使用队列存储待遍历顶点,将起始顶点入队。再依次执行:每次出队一个顶点,检查是否存在其余顶点,该顶点到其可达且之前的顶点均到其不可达。对这样的顶点,更新数组中其距离为该顶点距离加一,并入队。重复该过程直至队空或到目标顶点的距离已经被计算出。返回计算出的该距离即可。实现代码如下:
public int getDistance(Person person1, Person person2) {
if(!personList.contains(person1) || !personList.contains(person2))
return -2;
int size = personList.size();
int index1 = personList.indexOf(person1);
int index2 = personList.indexOf(person2);
int index;
int[] distance = new int[size];
ArrayList<Integer> queue = new ArrayList<Integer>();
Arrays.fill(distance, -1);
distance[index1] = 0;
queue.add(index1);
while(!queue.isEmpty()) {
index = queue.get(0);
for(int i = 0; i < size; i++) {
if(distance[index2] == -1 && distance[i] == -1 && relationNet.get(index).get(i) == 1 ) {
distance[i] = distance[index] + 1;
queue.add(i);
}
}
queue.remove(0);
}
return distance[index2];
}