topological_sort.m
来自「麻省理工学院的人工智能工具箱,很珍贵,希望对大家有用!」· M 代码 · 共 31 行
M
31 行
function order = topological_sort(A)% TOPOLOGICAL_SORT Return the nodes in topological order (parents before children).% order = topological_sort(adj_mat)n = length(A);indeg = zeros(1,n);zero_indeg = []; % a stack of nodes with no parentsfor i=1:n indeg(i) = length(parents(A,i)); if indeg(i)==0 zero_indeg = [i zero_indeg]; endendt=1;order = zeros(1,n);while ~isempty(zero_indeg) v = zero_indeg(1); % pop v zero_indeg = zero_indeg(2:end); order(t) = v; t = t + 1; cs = children(A, v); for j=1:length(cs) c = cs(j); indeg(c) = indeg(c) - 1; if indeg(c) == 0 zero_indeg = [c zero_indeg]; % push c end endend
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?