Build a Matrix With Conditions - Topological Sort [JS]
Description Solution: Topological Sort Use topological sort to find the order that each number should appear for both row and column conditions. If we can't process all nodes in the topological sort, that means we have a cycle and we return an empty matrix. Time Complexity: O(k^2) 299ms Space Complexity: O(k) (not including output) 61MB var buildMatrix = function ( k, rowConditions, colConditions ) { let rowOrder = getOrder(k + 1 , rowConditions); let colOrder = getOrder(k + 1 , colConditions); if (rowOrder === - 1 || colOrder === - 1 ) return []; let matrix = Array (k).fill( 0 ).map( () => Array (k).fill( 0 )); let pos = Array (k + 1 ).fill( 0 ).map( () => Array ( 2 )); for ( let i = 0 ; i < k; i++) { pos[rowOrder[i]][ 0 ] = i; pos[colOrder[i]][ 1 ] = i; } for ( let i = 1 ; i <= k; i++) { let [x, y] = pos[i]; matrix[x][y] = i; } return matrix; }; function getOrder ( n, edges ) { let inde...