Skip to content
New issue

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

Leetcode 2392. Build a Matrix With Conditions #136

Open
Woodyiiiiiii opened this issue Aug 28, 2022 · 0 comments
Open

Leetcode 2392. Build a Matrix With Conditions #136

Woodyiiiiiii opened this issue Aug 28, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Aug 28, 2022

题目给出了节点之间的前后关系,需要找出符合条件的其中一个排序,这种就是拓扑排序

拓扑排序实现方法:

  1. 遍历关系图,用双重数组存储一个节点对应其往后的节点关系
  2. 同时维护一个引用次数数组,保存对应每个节点的引用次数
  3. 维护一个节点队列,首先遍历引用次数数组,找到次数为0的节点,放入队列中,表示最先确定关系的节点
  4. 循环遍历节点队列直至为空,循环中,poll一个节点,找到其对应的子节点,将对应的子节点在引用次数数组中次数-1,如果次数为空,则放入队列中

拓扑排序得到先后顺序队列后:

  1. 判断队列大小是否等于所给值,小于的话说明不满足
  2. 放入二维数组中
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:

相似题目:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant