50,523
社区成员
发帖
与我相关
我的任务
分享
public class Sample {
public static void main(String[] args) {
int [][]num = { //测试数据
{3,4,2,5,3,8,4,6,9},
{22,28,16,6,27,21,30,1,29,10,9,14,24,11,7,2,8,5,26,4,12,3,25,18,20,19,23,17,13,15},
{2,3,4,4}
};
int max=-1, n;
List<Integer> tmp = new ArrayList<>(); //寻找用
List<Integer> res = new ArrayList<>(); //保存结果用
for (int j=0; j<num.length; j++) { //遍历取测试数据
max = -1;
res.clear();
for (int i=0; i<num[j].length; i++) { //此处以下是算法的开始,遍历崇拜关系
if (res.contains(i+1)) continue; //如果当前崇拜者被遍历过则跳过(只是为了改善性能,不要这行代码也没关系)
tmp.clear();
n = i+1; //当前崇拜者编号
tmp.add(n); //当前崇拜者加入环
while (true) { //一层层查找崇拜关系
n = num[j][n-1]; //取下一个崇拜者
if (!tmp.contains(n)) { //如果不在环中则加入环
tmp.add(n);
if (tmp.size() > num[j].length) break; //为了防止崇拜关系不正确而死循环(不存在环),正常可以不要这行代码
} else { //如果在环中(能形成环)
if (n!=i+1) {//如果最后一个崇拜者不是最开始的第一个崇拜者
tmp = tmp.subList(tmp.indexOf(n), tmp.size()); //则去掉不符合环的崇拜者
}
if (tmp.size()>max) { //如果环的人数大于max,则重新修改max,并保存环
max=tmp.size();
res.clear();
res.addAll(tmp);
}
break; //形成环则退出一层层查找崇拜关系
}
}
}
System.out.println(max); //打印最大环
System.out.println(res);
}
}
}
public void run() {
int[] nums = {22, 28, 16, 6, 27, 21, 30, 1, 29, 10, 9, 14, 24, 11, 7, 2, 8, 5, 26, 4, 12, 3, 25, 18, 20, 19, 23, 17, 13, 15};
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i< nums.length; i++) {
map.put(i, nums[i]);
}
Integer maxCircle = 0;
for (Integer v : map.values()) {
List<Integer> group = Lists.newArrayList();
int nodeCount = 0;
int i = v;
while (!group.contains(i)) {
group.add(i);
i = nums[i-1];
nodeCount ++;
if (nodeCount > maxCircle) {
maxCircle = nodeCount;
}
}
}
System.out.println(maxCircle);
}