博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
296. Best Meeting Point
阅读量:7045 次
发布时间:2019-06-28

本文共 1273 字,大约阅读时间需要 4 分钟。

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 , 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
>& grid) { vector
row; vector
col; for(int i = 0;i
> &distance,vector
> &counts,vector
>& grid) { int m = grid.size(); int n = grid[0].size(); vector
> visited(m,vector
(n,false)); visited[i][j] = true; counts[i][j] +=1; queue
> q; vector
> 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
=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; } } } } };

 

转载于:https://www.cnblogs.com/jxr041100/p/7885679.html

你可能感兴趣的文章
【HDU5785】Interesting [Manacher]
查看>>
数据结构(一)用类封装数组实现数据结构
查看>>
做题用到的C++或者C语言函数方法
查看>>
Java 初始化过程
查看>>
MySQL--3--运算符和函数
查看>>
dva/dynamic
查看>>
本地项目导入远程git仓库
查看>>
简单的汉诺塔问题
查看>>
uml类关系
查看>>
读杨绛先生的《我们仨》部分片段
查看>>
hdu 3853 LOOPS
查看>>
╮(╯_╰)╭周五了,捋捋。话说,静不下心来!
查看>>
Android的弹出登陆框的实现
查看>>
python数据库(mysql)操作
查看>>
博客打开慢?请禁用WordPress默认的谷歌字体!
查看>>
如何循环枚举类型
查看>>
FAQ软件卸载
查看>>
谈谈多线程的思维方式
查看>>
cocos2d-x中使用sqlite
查看>>
springMVC 实现ajax跨域请求
查看>>