|
| 1 | +% Returns a graph object representing the possible moves in a game of Hanoi |
| 2 | +% with numOfDisks disks and numOfPegs pegs. |
| 3 | +% |
| 4 | +% Each node is a state of the Hanoi game and each edge is a move. |
| 5 | +% |
| 6 | +% A state is represented with a vector whreich has numOfDisks elements and |
| 7 | +% the k-th element represents the current position of (numOfDisks - k)-th |
| 8 | +% disk. So if we have a game of 3 disks and 3 pegs and the state is [1 2 |
| 9 | +% 3], the smallest disk is on the third peg and the biggest is on the first |
| 10 | +% peg. |
1 | 11 | function G = hanoi(numOfDisks, numOfPegs)
|
2 | 12 | numOfNodes = numOfPegs^numOfDisks;
|
3 | 13 | numOfEdges = 0;
|
|
12 | 22 | toVector = numberToVectorInBase(to - 1);
|
13 | 23 |
|
14 | 24 | if isValidEdge(fromVector, toVector)
|
15 |
| - %disp([getNameOfNode(fromVector), ' ', getNameOfNode(toVector)]); |
16 | 25 | beginEdge(numOfEdges + 1) = from;
|
17 | 26 | endEdge(numOfEdges + 1) = to;
|
18 | 27 | numOfEdges = numOfEdges + 1;
|
|
24 | 33 |
|
25 | 34 | G = graph(beginEdge, endEdge, ones(1, numOfEdges), names);
|
26 | 35 |
|
| 36 | + % Checks if an edge is a valid move in Hanoi |
| 37 | + % For it to be valid, it needs to satisfy three conditions: |
| 38 | + % |
| 39 | + % 1) Only one disk can be moved in one move |
| 40 | + % 2) You cannot move a disk which has a smaller disk on it |
| 41 | + % 3) You cannot move a disk to a peg which already has a smaller disk |
| 42 | + % on it |
| 43 | + % |
| 44 | + % Returns 1 if it is valid, 0 if it is invalid |
27 | 45 | function validEdge = isValidEdge(fromVector, toVector)
|
28 | 46 | numOfChanges = 0;
|
29 | 47 | firstChanged = -1;
|
|
0 commit comments