File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * memoization
5+ *
6+ * m: length of matrix
7+ * n: length of matrix[i]
8+ * time complexity: O(m * n)
9+ * space complexity: O(m * n)
10+ */
11+ var setZeroes = function ( matrix ) {
12+ const stack = [ ] ;
13+ const memo = { row : new Set ( ) , column : new Set ( ) } ;
14+
15+ const setZero = ( { r, c, isRow, isColumn } ) => {
16+ const length = isRow ? matrix . length : matrix [ 0 ] . length ;
17+
18+ for ( let i = 0 ; i < length ; i ++ ) {
19+ const row = isRow ? i : r ;
20+ const column = isColumn ? i : c ;
21+ matrix [ row ] [ column ] = 0 ;
22+ }
23+ } ;
24+
25+ matrix . forEach ( ( row , r ) => {
26+ row . forEach ( ( value , c ) => {
27+ if ( value === 0 ) stack . push ( [ r , c ] ) ;
28+ } ) ;
29+ } ) ;
30+
31+ while ( stack . length ) {
32+ const [ r , c ] = stack . pop ( ) ;
33+
34+ if ( ! memo . row . has ( r ) ) {
35+ setZero ( { r, c, isColumn : true } ) ;
36+ memo . row . add ( r ) ;
37+ }
38+
39+ if ( ! memo . column . has ( c ) ) {
40+ setZero ( { r, c, isRow : true } ) ;
41+ memo . column . add ( c ) ;
42+ }
43+ }
44+
45+ return matrix ;
46+ } ;
You can’t perform that action at this time.
0 commit comments