File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } k
3+ * @param {number[][] } rowConditions
4+ * @param {number[][] } colConditions
5+ * @return {number[][] }
6+ */
7+ var buildMatrix = function ( k , rowConditions , colConditions ) {
8+ const res = Array . from ( { length : k } , ( ) => Array ( k ) . fill ( 0 ) ) ;
9+
10+ const row = khansAlgo ( rowConditions , k ) ;
11+ if ( row . length != k ) return [ ] ;
12+
13+ const col = khansAlgo ( colConditions , k ) ;
14+ if ( col . length != k ) return [ ] ;
15+
16+ const idx = Array ( k + 1 ) . fill ( 0 ) ;
17+ for ( let j = 0 ; j < col . length ; j ++ ) {
18+ idx [ col [ j ] ] = j ;
19+ }
20+ for ( let i = 0 ; i < k ; i ++ ) {
21+ res [ i ] [ idx [ row [ i ] ] ] = row [ i ] ;
22+ }
23+ return res ;
24+
25+ function khansAlgo ( r , k ) {
26+ const cnt = Array ( k + 1 ) . fill ( 0 )
27+ const adj = Array . from ( { length : k + 1 } , ( ) => Array ( ) )
28+
29+ for ( let x of r ) {
30+ cnt [ x [ 1 ] ] ++ ;
31+ adj [ x [ 0 ] ] . push ( x [ 1 ] ) ;
32+ }
33+ const row = [ ] ;
34+ const q = [ ] ;
35+ for ( let i = 1 ; i <= k ; i ++ ) {
36+ if ( cnt [ i ] == 0 ) {
37+ q . push ( i ) ;
38+ }
39+ }
40+ while ( q . length ) {
41+ let t = q . pop ( ) ;
42+
43+ row . push ( t ) ;
44+ for ( let x of ( adj [ t ] || [ ] ) ) {
45+ cnt [ x ] -- ;
46+ if ( cnt [ x ] == 0 ) {
47+ q . push ( x ) ;
48+ }
49+ }
50+ }
51+ return row ;
52+ }
53+ } ;
54+
55+ // another
56+
157/**
258 * @param {number } k
359 * @param {number[][] } rowConditions
You can’t perform that action at this time.
0 commit comments