, " " Cormen, Leiserson, Rivest Stein, 2nd Edition. 24 " ", 24.3 .
. , Java. , , . Java , .
, , 2D-, : int [M] [N] . - , - , . , 0 M-1 0 N-1 . [] [] , (, ). , , .
, : row1, row2,..., rowM. . , : (, ) → → (, ).
convert_to_index(row, column) ::= row * N + column
convert_to_pair(i) ::= (i div N, i modulo N)
, SIZE - M * N, .
, : int [SIZE] [SIZE] adjacency_matrix, - FROM, - TO. , . , , . . , INFINITY. 0 9. , .
, (r, c), ? , . , : (r-1, c-1), (r-1, c), (r-1, c + 1), (r, c-1), (r, c + 1), (r + 1, c-1), (r + 1, c) (r + 1, c + 1). convert_to_index , , 0..SIZE-1 . , , (r, c) (r-1, c-1) [r-1, c-1] (r-1, c-1) (r, c) [r, c]. (r, c) 10, , .
adjacent_rooms(r, c) ::=
Given the vector [(r-1, c-1), (r-1, c), (r-1, c+1), (r, c-1), (r, c+1), (r+1, c-1), (r+1, c), (r+1,c+1)]
Filter it by deleting pairs whose row is not in 0..M-1 or whose column is not in 0..N-1
Then apply the function convert_to_index to each resulting pair (map operation)
Return the result
for i in 0..SIZE-1 loop
for j in 0..SIZE-1 loop
adjacency_matrix[i, j] := -1
end loop
end loop
for i in 0..SIZE-1 loop
(current_r, current_c) := convert_to_pair(i)
adjacent_room_indexes := adjacent_rooms(current_r, current_c)
for j in 0..SIZE-1 loop
if adjacency_matrix[i, j] == -1 then
(r, c) := convert_to_pair(j)
if i == j then adjacency_matrix[i, j] := 0
elsif j in adjacent_room_indexes then adjacency_matrix[i, j] := maze[r, c]; adjacency_matrix[j, i] := maze[current_r, current_c]
else adjacency_matrix[i, j] := INFINITY
end if
end loop
end loop
(. 585) (. 584).
for i in 0..SIZE-1 loop
predecessors[i] := NONE
estimates[i] := INFINITY
end loop
0.
estimates[0] := 0
, MST ( )
mst := empty set
- q
for i in 0..SIZE-1 loop
q.add(i, estimates[i])
end loop
until q.empty? loop
u, u_d = q.delete_min
mst.add(u)
(current_r, current_c) := convert_to_pair(i)
adjacent_room_indexes := adjacent_rooms(current_r, current_c)
for i in 0..adjacent_room_indexes.length-1 loop
v := adjacent_room_indexes[i]
cost = adjacency_matrix[u, v]
if cost < q[v]
predecessors[v] = u
estimates[v] = c
q[v] = c
end
end loop
end loop
. predecessors estimates.
, A * . , Dijkstra . A *, A * Pathfinding Amits A * Pages.