I'm looking for some advice on how to tackle this problem.
You're given a binary matrix of 1s and 0s, and the goal is to find the shortest path that visits every 1.
For example:
1 0 0 0
0 0 1 0
1 0 1 1
0 0 0 1
The shortest path (I think) to visit all ones is something like this:
1 0 0 0
0 0 1 0
1 0 1 1
0 0 0 1
In any case, I believe this is a traveling salesman type of problem or possibly a minimum spanning tree. However, I'm completely unsure how to even get started. This is not a typical graph search as you technically don't have neighbors or costs, and there is no predefined start node; you can start or end at any position. Does anyone have any suggestions? Thank you very much.

- 11
- 4
1 Answers
This is a TSP. Define the set of nodes V
as the set of 1s in the matrix. Define the distance d(i,j)
between any i
and j
in V
as the distance within the matrix. If I'm understanding your example correctly, you are allowed to "move" only vertically or horizontally in the matrix. So d(i,j) = |i_x - j_x| + |i_y - j_y|
, where (i_x,i_y)
are the coordinates (row and column number) of node i
, and similarly for j
. (This is also called Manhattan metric, rectilinear metric, or L1 norm.)
It seems like you want a path rather than a cycle -- start anywhere and end anywhere. Classical TSP assumes you start and end at the same node. Simple fix: Create a dummy node and set the distance to/from the dummy node from/to any other node to 0. Then just ignore the edges to/from the dummy node in the optimal TSP tour.

- 2,277
- 12
- 24