Java Reference
In-Depth Information
57
else
58 node[row *
3
+ column] =
'H'
;
// Flip from T to H
59 }
60 }
61
62
For example:
public static int
getIndex(
char
[] node) {
get index for a node
63
int
result =
0
;
index: 3
64
65
for
(
int
i =
0
; i <
9
; i++)
66
if
(node[i] ==
'T'
)
67 result = result *
2
+
1
;
68
else
69 result = result *
2
+
0
;
70
71
node: HHHHHHHTT
H H H
H H H
H T T
return
result;
72 }
73
74
For example:
public static char
[] getNode(
int
index) {
get node for an index
75
char
[] result =
new char
[
9
];
node: THHHHHHTT
index: 259
76
77
for
(
int
i =
0
; i <
9
; i++) {
78
int
digit = index %
2
;
79
if
(digit ==
0
)
80 result[
8
- i] =
'H'
;
81
else
82 result[
8
- i] =
'T'
;
83 index = index /
2
;
84 }
85
86
T H H
H H H
H T T
return
result;
87 }
88
89
public
List<Integer> getShortestPath(
int
nodeIndex) {
shortest path
90
return
tree.getPath(nodeIndex);
For example:
91 }
92
93
public static void
printNode(
char
[] node) {
94
for
(
int
i =
0
; i <
9
; i++)
95
if
(i %
3
!=
2
)
96 System.out.print(node[i]);
97
else
98 System.out.println(node[i]);
99
100 System.out.println();
101 }
102 }
node:
THHHHHHTT
Output:
display a node
T H H
H H H
H T T
The constructor (lines 8-18) creates a graph with 512 nodes, and each edge corresponds to
the move from one node to the other (line 10). From the graph, a BFS tree rooted at the target
node
511
is obtained (line 17).
To create edges, the
getEdges
method (lines 21-37) checks each node
u
to see
if it can be flipped to another node
v
. If so, add (
v
,
u
) to the
Edge
list (line 31). The
getFlippedNode(node, position)
method finds a flipped node by flipping an
H
cell
and its neighbors in a node (lines 43-47). The
flipACell(node, row, column)
method
actually flips an
H
cell and its neighbors in a node (lines 52-60).
The
getIndex(node)
method is implemented in the same way as converting a binary
number to a decimal number (lines 62-72). The
getNode(index)
method returns a node
consisting of the letters
H
and
T
(lines 74-87).
Search WWH ::
Custom Search