Minimum/maximum distance

The solution is from [1]. [1] also introduces several solutions for the variations of this problem.

class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
vector<int> x, y;
const int R = grid.size(), C = grid[0].size();
for(int i = 0; i<R;++i )
for(int j=0;j<C;++j)
{
if(grid[i][j]==1)
{
x.push_back(j);
y.push_back(i);
}
}
sort(x.begin(), x.end());
sort(y.begin(), y.end());
int mx = x[x.size()/2], my = y[y.size()/2];
int ret = 0;
for(int i = 0;i<x.size();++i)
{
ret += (abs(mx-x[i])+abs(my-y[i]));
}
return ret;
}
};

1515. Best Position for a Service Centre

See my previous post HERE.

Reference

[1]https://youtu.be/Klf0EVLsKqs

--

--

--

Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

week one

🏆 Re:water Wallet Airdrop

Automate the building and deployment of a Docker image in Azure

Volumino Instal Mac Seperate App

How to Serverless — Production Ready APIs on the Go

Metaverse Event with Toyota Tsusho Corporation

Can You Learn to Code For Less Than $100?

Box co-founder on moving to microservices, and the promise of Kubernetes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Kruskal’s algorithm

Binary Neural Network part 2

機器學習動手做Lesson 25 — Variation of Information Distance 是檢測集成分群效果的好方法

Are thermal fuses part of planned obsolescence?