We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
题目给出了节点之间的前后关系,需要找出符合条件的其中一个排序,这种就是拓扑排序。
拓扑排序实现方法:
拓扑排序得到先后顺序队列后:
class Solution { public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) { // topological sort List<Integer> list1 = buildList(k, rowConditions); List<Integer> list2 = buildList(k, colConditions); // validate if (list1.size() < k || list2.size() < k) { return new int[0][0]; } // connection Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < list2.size(); i++) { map.put(list2.get(i), i); } // build matrix int[][] matrix = new int[k][k]; for (int i = 0; i < list1.size(); i++) { matrix[i][map.get(list1.get(i))] = list1.get(i) + 1; } return matrix; } private List<Integer> buildList(int k, int[][] a) { int[] cnt = new int[k]; Queue<Integer> queue = new LinkedList<>(); List<Integer> res = new ArrayList<>(); List<List<Integer>> list = new ArrayList<>(k); for (int i = 0; i < k; ++i) { list.add(new ArrayList<>()); } for (int[] b : a) { cnt[b[1] - 1]++; list.get(b[0] - 1).add(b[1] - 1); } for (int i = 0; i < k; ++i) { if (cnt[i] == 0) { queue.offer(i); } } while (!queue.isEmpty()) { int cur = queue.poll(); res.add(cur); for (int next : list.get(cur)) { cnt[next]--; if (cnt[next] == 0) { queue.offer(next); } } } return res; } }
References:
相似题目:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目给出了节点之间的前后关系,需要找出符合条件的其中一个排序,这种就是拓扑排序。
拓扑排序实现方法:
拓扑排序得到先后顺序队列后:
References:
相似题目:
The text was updated successfully, but these errors were encountered: