This problem is a variation. The longest path problem , however, your limitations make this problem much simpler because the graph is actually a Directional Acyclic Graph (DAG) , and therefore, the problem can be effectively solved.
Define a directed graph G=(V,E) as follows:
V = { all cells in the matrix} (health check: | V | = N ^ 2)E = { (u,v) | u is adjacent to v AND value(u) + 1 = value(v) }
Note that the resulting graph from the above definition is DAG, because you cannot have any loops, as this will result in some edge e= (u,v) such as value(u) > value(v) .
Now you need to find the longest path in the DAG from any starting point. This is done using topological sorting on the graph, and then using dynamic programming:
init: for every source in the DAG: D(v) = 0 if value(v) = 0 -infinity otherwise step: for each node v from first to last (according to topological sort) D(v) = max{D(u) + 1 | for each edge (u,v) }
When you're done, find node v with the maximum value of D(v) , this is the length of the longest "good path".
The search for the path itself is performed by repeating the above, re-returning your steps back from the maximum D (v) until you return to the original node with a value of 0.
The complexity of this approach is O(V+E) = O(n^2)
Since you are looking for the number of longest paths, you can slightly modify this solution to calculate the number of paths reached for each node, as follows:
Topological sort the nodes, let the sorted array be arr (1) For each node v from start to end of arr: if value(v) = 0: set D(v) = 1 else sum = 0 for each u such that (u,v) is an edge: (2) sum = sum + D(u) D(v) = sum
The above will find for each node v number of "good paths" D(v) that will achieve this. All you have to do now is find the maximum value of x that the sum of node v , such that value(v) = x and D(v) > 0 and sum the number of paths reaching any node using value(v) :
max = 0 numPaths = 0 for each node v: if value(v) == max: numPaths = numPaths + D(v) else if value(v) > max AND D(v) > 0: numPaths = D(v) max = value(v) return numPaths
Notes: (1) - the “regular” view works here, but it will take the time O (n ^ 2logn), and the topological sort takes the time O (n ^ 2)
(2) Reminder, (u, v) is an edge if: (1) u and v are adjacent (2) value (u) + 1 = value (v)