I have a spreadsheet application with formulas. I am looking for the best algorithm for detecting circular references among the formulas. The current approach I have is slow and uses too much memory when long chains of calculations are in place with the formulas. It involves keeping sets of all dependents for each formula. So if the first column of cells each had a formula with a reference to the cell before it, the first cell's set would be empty. The 2nd cell's set would only contain the first cell, the 3rd cell's set would contain cells 1 and 2, ..., the 1000th cell's set would contain the 999 cells before it. When a new formula was introduced, its dependents set is built and if the set contains the new formula, there is a circular reference. But obviously, for this scenario, the time and memory required grows exponentially.
Asked
Active
Viewed 4,249 times
6
-
[this](http://stackoverflow.com/questions/546655/finding-all-cycles-in-graph) answer might be of help – abeln Apr 20 '11 at 15:20
3 Answers
5
You need to do a topological sorting of the cells anyway in order to be able to rapidly calculate the values of cells when something is changed. The topological sorting procedure also detect cycles as a byproduct.

Antti Huima
- 25,136
- 3
- 52
- 71
-
Thanks. I already had a fast algorithm for sorting the formulas and detecting changes, but now I can remove that and kill two birds with one stone with this. – Mike Dour Apr 20 '11 at 21:20
1
Represent the dependencies between cells as a directed graph, and use Tarjan's strongly connected components algorithm (each strongly connected component of size 2 or larger contains cycles).

Gareth Rees
- 64,967
- 9
- 133
- 163
0
Perhaps you have motives for checking on your own, but Excel already checks for circular references automatically. You can use the Worksheets.CircularReference
property in VBA to access this information.

Excellll
- 5,609
- 4
- 38
- 55
-
The data is not in an Excel workbook. I just tagged this question with Excel because it is so closely related to an Excel scenario. – Mike Dour Apr 20 '11 at 20:02