File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -53,3 +53,45 @@ function min(arr) {
5353 }
5454 return sum
5555}
56+
57+ // another
58+
59+ /**
60+ * @param {number[][] } grid
61+ * @return {number }
62+ */
63+ const minTotalDistance = function ( grid ) {
64+ const homeArr = [ ]
65+ const horiArr = [ ] , vertArr = [ ]
66+ const m = grid . length ,
67+ n = grid [ 0 ] . length
68+ for ( let i = 0 ; i < m ; i ++ ) {
69+ for ( let j = 0 ; j < n ; j ++ ) {
70+ if ( grid [ i ] [ j ] === 1 ) {
71+ homeArr . push ( [ i , j ] )
72+ vertArr . push ( i )
73+ horiArr . push ( j )
74+ }
75+ }
76+ }
77+
78+ vertArr . sort ( ( a , b ) => a - b )
79+ horiArr . sort ( ( a , b ) => a - b )
80+
81+ let y = vertArr [ ~ ~ ( vertArr . length / 2 ) ]
82+ let x = horiArr [ ~ ~ ( horiArr . length / 2 ) ]
83+
84+ const center = [ y , x ]
85+
86+ let res = 0
87+ for ( const point of homeArr ) {
88+ res += dis ( center , point )
89+ }
90+
91+ return res
92+
93+ function dis ( a , b ) {
94+ return Math . abs ( a [ 0 ] - b [ 0 ] ) + Math . abs ( a [ 1 ] - b [ 1 ] )
95+ }
96+
97+ }
You can’t perform that action at this time.
0 commit comments