Here's a non-recursive MiniZinc pathfinding model that avoids syntax errors and ensures correctness by safely handling empty paths. This version guarantees the shortest path from a source to a target node in a directed graph.
✅ Corrected MiniZinc Model
% Parameters
int: n; % Number of nodes
set of int: NODES = 1..n;
% Adjacency matrix: cost[i,j] is the cost from i to j, or 0 if no edge
array[NODES, NODES] of int: cost;
int: source;
int: target;
% Large value to represent unreachable (simulate infinity)
int: INF = 1000000;
% Decision Variables
array[NODES] of var 0..INF: dist;
% Constraints
constraint dist[source] = 0;
% For each node i ≠ source, dist[i] is the minimum of all incoming paths
constraint forall(i in NODES where i != source)(
dist[i] =
min(
[dist[j] + cost[j,i] | j in NODES where cost[j,i] > 0] ++ [INF]
)
);
% Ensure the target is reachable
constraint dist[target] < INF;
% Objective: minimize the distance to the target node
solve minimize dist[target];
% Output
output ["Shortest path cost to node ", show(target), ": ", show(dist[target])];
📦 Example Data File (data.dzn)
n = 5;
cost = array2d(1..5, 1..5, [
0, 3, 2, 0, 0,
0, 0, 0, 4, 0,
0, 0, 0, 5, 0,
0, 0, 0, 0, 1,
0, 0, 0, 0, 0
]);
source = 1;
target = 5;
🧠 Key Improvements
| Feature | Description |
|---|
| Avoids Empty Array Errors | Uses ++ [INF] to ensure the min() function always receives a non-empty list |
| Non-Recursive | No recursive functions or loops; fully declarative |
| Safe Infinity Handling | Replaces actual infinity with a large value (INF) to avoid syntax issues |
| Guarantees Reachability | Enforces dist[target] < INF to ensure the target is reachable |
🧪 How It Works
dist[source] = 0: Sets the distance from the source to itself as 0.
min([dist[j] + cost[j,i] | j in NODES where cost[j,i] > 0] ++ [INF]):
- Computes the shortest distance to node
i by checking all incoming edges.
- If no incoming edges exist, the list is not empty due to
++ [INF], so dist[i] = INF.
dist[target] < INF:
- Ensures that the target is reachable; otherwise, the model is unsatisfiable.
🚫 Why the Previous Version Failed
- Empty List in
min(): If no incoming edge exists for a node, the expression [dist[j] + cost[j,i] | j in NODES where cost[j,i] > 0] is empty, and min() fails.
- Improper Use of
exists(): It only checks for the existence of a path but does not enforce the shortest path condition.
- Syntax Errors with
infinity: MiniZinc does not support the infinity keyword in constraints directly.
✅ Example Output
For the provided data.dzn:
Shortest path cost to node 5: 8
Which corresponds to the path: 1 → 3 → 4 → 5 with total cost 2 + 5 + 1 = 8.
📌 Final Notes
- This model is robust and avoids all syntax and logic errors from previous versions.
- It is suitable for graphs with positive edge weights and no negative cycles.
- If you need to reconstruct the actual path, let me know — I can provide a non-recursive version of that as well.
Would you like the path reconstruction added to this model?