Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Interesting one.. I can feel sparkle in mind in the proposed solution - just pick the mid-point! (yes some boiler-plate code below)

class Solution {
    //    Greedy solution
public:
    int minTotalDistance(vector<vector<int>>& grid) {
        int n = grid.size();
    int m = grid[0].size();
    
    // Record - O(m*n)
    vector<int> hori(m);
    vector<int> vert(n);
    for(int i = 0; i < n; i++)
    for(int j = 0; j < m; j++)
    {
        if(grid[i][j])
        {
        hori[j]++;
        vert[i]++;
        }
    }
    
    // Expand records - O(k)
    vector<int> horis, verts;
    for(int i = 0; i < hori.size(); i ++)
    {
        int v = hori[i];
        if(v)
        {
        for(int j = 0; j < v; j++)
            horis.push_back(i);
        }
    }
    for(int i = 0; i < vert.size(); i ++)
    {
        int v = vert[i];
        if(v)
        {
        for(int j = 0; j < v; j++)
            verts.push_back(i);
        }
    }
    
    // Get point coords
    size_t hcnt = horis.size(), vcnt = verts.size();
    int mid_h = (hcnt % 2) ? horis[hcnt/2] : ((horis[hcnt/2] + horis[hcnt/2 - 1]) / 2);
    int mid_v = (vcnt % 2) ? verts[vcnt/2] : ((verts[vcnt/2] + verts[vcnt/2 - 1]) / 2);
    
    int ret = 0;
    
    for(int i = 0; i < n; i++)
    for(int j = 0; j < m; j++)
    {
        if(grid[i][j])
        {
        ret += abs(i - mid_v) + abs(j - mid_h);
        }
    }
    
    return ret;
    }
};
posted on 2015-10-23 13:19  Tonix  阅读(188)  评论(0编辑  收藏  举报