296. Best Meeting Point

A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

For example, given three people living at (0,0)(0,4), and (2,2):

1 - 0 - 0 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0

The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.

class Solution {
public:
    int minTotalDistance(vector<vector<int>>& grid) {
        vector<int> row;
        vector<int> col;
        for(int i = 0;i<grid.size();i++)
            for(int j = 0;j<grid[0].size();j++)
                if(grid[i][j])
                {
                    row.push_back(i);
                    col.push_back(j);
                }
        sort(row.begin(),row.end());
        sort(col.begin(),col.end());
        
        int mid_row = row.size()%2? row[row.size()/2]: (row[row.size()/2 - 1] + row[row.size()/2]) / 2;
        int mid_col = col.size()%2? col[col.size()/2]: (col[col.size()/2 - 1] + col[col.size()/2]) / 2;

        int dist = 0;
        for(int i = 0; i<row.size(); i++) dist += abs(mid_row - row[i]);
        for(int i = 0; i<col.size(); i++) dist += abs(mid_col - col[i]);

        return dist;
        
        
    }
private:
    void bfs(int i,int j,vector<vector<int>> &distance,vector<vector<int>> &counts,vector<vector<int>>& grid)
    {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> visited(m,vector<int>(n,false));
        visited[i][j] = true;
        counts[i][j] +=1;
        queue<pair<int,int>> q;
        vector<pair<int,int>> dirs = {{-1,0},{1,0},{0,-1},{0,1}};
        q.push({i,j});
        int step = 0;
        while(!q.empty())
        {
            int N = q.size();
            step++;
            for(int i = 0;i<N;i++)
            {
                int r = q.front().first;
                int c = q.front().second;
                q.pop();
                for(auto dir:dirs)
                {
                    int nextr = r+dir.first;
                    int nextc = c+dir.second;
                    if(nextr<0 || nextr>=m || nextc<0 || nextc>=n || visited[nextr][nextc]) continue;
                    visited[nextr][nextc] = true;
                    q.push({nextr,nextc});
                    distance[nextr][nextc]+=step;
                    counts[nextr][nextc]+=1;
                }  
            }
        }
    }
    
};

 

posted @ 2017-11-23 16:44  jxr041100  阅读(132)  评论(0编辑  收藏  举报