I have a simple weighted graph
A
1 / \\ 0.5
/ \\0.5
B C
Suppose this describes a family and A is the father, B is the son and C is the mother. Let's say B is studying in an university and A has bought an apartment for him. A is living with C in a house which is commonly owned, 50-50.
I want to transform the graph into a tree, starting from A: ie.
- A owns 50% of the place C is living in
- A owns 100% of the place B is living in
- C owns 50% of the place A is living in
The graph and the generated tree could be more elaborate but I hope you get the more general picture.
On SQL Server 2005 I have
Drop Table #graph;
Create Table #graph
(FirstVertex VarChar(1) Not Null,
SecondVertex VarChar(1) Not Null,
Weight float);
Insert #graph Values('A','B',1);
Insert #graph Values('A','C',0.5);
Insert #graph Values('C','A',0.5);
and I'm using the following common table expression to traverse the graph, starting from 'A':
With GraphRecursion (FirstVertex, SecondVertex, Weight, Level)
As
(
Select FirstVertex, SecondVertex, Weight, 0 As Level
From #graph
Where FirstVertex='A'
Union all
Select a.FirstVertex, a.SecondVertex, a.Weight, b.Level+1
From #graph a
Inner Join GraphRecursion b
On a.FirstVertex=b.SecondVertex --And b.Level<=1
)
Select * From GraphRecursion;
This causes
Msg 530, Level 16, State 1, Line 11
The statement terminated. The maximum recursion 100 has
been exhausted before statement completion.
Limiting the level of recursion by uncommenting the And b.Level<=1
gives the expected results, but that's obviously not very useful for any practical use.
Is there a way to reference the previous iterations so that in the above example edges (ie. the FirstVertex, SecondVertex pairs) would not be repeated?