简体   繁体   中英

Distance between two cells in a 2D matrix

I have a 2D matrix represented as a vector of values, an index representing the first cell and a pair of coordinate representing the second cell.

vector<double> matrix;
auto index = 10;

auto x1 = index % width;
auto y1 = index / width;
auto x2 = ...
auto y2 = ...

I need to find the distance between these two cells, where the distance is equals to 1 for the first "ring" of the 8 neighbor cells, 2 for the second ring, and so on.

Is there a way faster than the euclidean distance?

What you need is something like a modified Manhattan Distance . I think there may be a specific name for your use case, but I don't know it. Anyway, this is how I'd do it.

Suppose the two points are x rows away and y columns away. Then x+y is the Manhattan Distance. But in your case, diagonal movements are also allowed. So, if you moved diagonally towards the point initially, you'd cover the smaller of x and y , with some amount remaining in the other. You can then move horizontally/vertically to cover the remaining distance. Hence, the distance by your metric would be max(x,y) .

Given points (x1,y1) and (x2,y2) , the answer would be max(|x1-x2|,|y1-y2|)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM