Matrix Cells in Distance Order Solutions in C++
Number 1030
Difficulty Easy
Acceptance 65.7%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/matrix-cells-in-distance-order/// Author : Hao Chen// Date : 2019-04-21class Solution {public:void put(int R, int C, int r, int c, vector<vector<int>>& res) {if (r>=0 && r < R && c>=0 && c<C ) {res.push_back({r,c});}}vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {int n = R+C-2;vector<vector<int>> result;result.push_back({r0,c0});for(int i=1; i<= n; i++) {// from (r0-i, c0) to (r0, c0+i)for(int r=r0-i,c=c0;r!=r0; r++, c++) put (R, C, r ,c, result);// from (r0, c0+i) to (r0+i, c0)for(int r=r0, c=c0+i; c!=c0; r++, c-- ) put (R, C, r, c, result);// from (r0+i, c0) to (r0, c0-i)for (int r=r0+i, c=c0; r!=r0; r--, c--) put (R, C, r, c, result);// from (r0, c0-i) to (r0-i, c0)for (int r=r0, c=c0-i; c!=c0; r--, c++) put (R, C, r, c, result);}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/matrix-cells-in-distance-order//// Author : liuyubobobo/// Time : 2019-04-20#include <iostream>#include <vector>using namespace std;/// Greedy/// Time Complexity: O(nlogn)/// Space Complexity: O(n)class Solution {public:int twoCitySchedCost(vector<vector<int>>& costs) {vector<vector<int>> A, B;int res = 0;for(const vector<int>& cost: costs)if(cost[0] < cost[1])res += cost[0], A.push_back(cost);elseres += cost[1], B.push_back(cost);vector<vector<int>>& t = A.size() < B.size() ? B : A;sort(t.begin(), t.end(), [](const vector<int>& v1, const vector<int>& v2){return abs(v1[0] - v1[1]) > abs(v2[0] - v2[1]);});while(t.size() > costs.size() / 2){res += abs(t.back()[0] - t.back()[1]);t.pop_back();}return res;}};int main() {return 0;}