import cn.hutool.json.JSONUtil;
import java.util.*;
public class Test {
public static void main(String[] args) {
int[][] a = new int[4][2];
a[0] = new int[]{0,1};
a[1] = new int[]{0,2};
a[2] = new int[]{3,0};
a[3] = new int[]{2,1};
System.out.println(JSONUtil.toJsonStr(findOrder(4,a)));
}
public static int[] findOrder(int nodeCount, int[][] edges) {
//先找到起点
Map<Integer,Integer> head = new HashMap<>();
for (int[] edge:edges) {
//线起点个数
Integer num = head.get(edge[0]);
if (num == null){
head.put(edge[0],1);
} else {
head.put(edge[0],num+1);
}
}
Integer start = null;
for (Integer key:head.keySet()) {
if (head.get(key) == 1){
start = key;
}
}
//遍历线段后得到的路径
List<Integer> path = new ArrayList<>();
path = buildPath(path,edges,start);
//[3,0,0,1,0,2,2,1]
//逆序合并相同节点
List<String> list = new ArrayList<>();
int index = 0;
for (int j = path.size() -1;j>= 0 ; j-- ) {
if (!list.contains(path.get(j)+"")){
list.add(path.get(j)+"");
}
}
int k = 0;
int[] ret = new int[nodeCount];
for (int j = list.size() -1;j>= 0 ; j-- ) {
ret[k++] = Integer.valueOf(list.get(j));
}
return ret;
}
private static List<Integer> buildPath(List<Integer> path, int[][] edges, Integer start) {
//当前起点
for (int i = 0; i <edges.length ;i++) {
int[] edge = edges[i];
if (edge[0] == start){
path.add(edge[0]);
path.add(edge[1]);
buildPath(path,edges,edge[1]);
}
}
return path;
}