Given a grid of width by length (say 5 x 4) and an array of X and Y coords for points on that grid, print the distance from each point on the grid to the coords as below:
width = 5
len = 4
x coords = (2,3)
y coords = (2,4)
for i .. width
for j .. length
I assume that you are looking for the distance to the nearest
coord among the ones given in the vector, i.e.
for i 0 .. width for j 0 .. length best = distance(i, j, coords.x, coords.y) for k 1 .. coordVector // Skip first element best = min(best, distance(i, j, coords[k].x, coords[k].y) result[i][j] = best
The third nested loop checks the distance from the given coordinate to all coordinates in the vector of (xi, yi), picks the shortest one, and stores it in the variable
best. Note that
best is initialized with the distance to the first point in the vector, so the nested loop starts with the second point.
All you need now is a calculator for
distance. According to the problem description, you are looking for Manhattan Distance because a diagonal step is weighted as 2, meaning it's the same as one step horizontally plus one step vertically:
distance(x0, y0, x1, y1) horizontal = abs(x1-x0) vertical = abs(y0-y1) return horizontal + vertical