-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS_algorithm.m
More file actions
30 lines (29 loc) · 870 Bytes
/
BFS_algorithm.m
File metadata and controls
30 lines (29 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function [path] = BFS_algorithm(AdjTable, start_node, goal_node)
% input: a graph in the form of an adjacency table, a start node, and a
% goal node
% output: a path from start node to goal node if it exists, otherwise a
% failure notice
parent = {};
for i = 1:length(AdjTable)
parent{i} = nan;
end
parent{start_node} = start_node;
% create empty queue and insert start node
Q = [];
Q = [Q; start_node];
while ~isempty(Q)
% retrieve item that sits at front of queue
v = Q(1);
Q(1) = [];
% for each node u connected to v by an edge
for u = AdjTable{v}
if isnan(parent{u})
parent{u} = v;
Q = [Q; u];
end
if u == goal_node
% run extract-path alogorithm to extract path
[path] = extract_path_algorithm(goal_node, parent);
end
end
end