Leetcode 296 Solution

This article provides solution to leetcode question 296 (best-meeting-point)

https://leetcode.com/problems/best-meeting-point

Solution

class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { if (grid.size() == 0 || grid[0].size() == 0) return 0;
int m = grid.size(); int n = grid[0].size(); vector<int> a1; vector<int> a2;
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { a1.push_back(i); a2.push_back(j); } } }
sort(a2.begin(), a2.end());
int k = a1.size(); int res = 0; for (int i = 0; i < k; i++) { res += abs(a1[i] - a1[k / 2]); res += abs(a2[i] - a2[k / 2]); }
return res; } };