1function v = bfs_matlab (A, s) 2%BFS_MATLAB a simple breadth-first-search in MATLAB 3% 4% v = bfs_matlab (A, s) 5% 6% A is a square binary matrix, corresponding to the adjacency matrix of a 7% graph, with A(i,j)=1 denoting the edge (i,j). Self loops are permitted, and 8% A may be unsymmetric. s is a scalar input with the source node. The output 9% v is the level each node in the graph, where v(s)=1 (the first level), v(j)=2 10% if there is an edge (s,j) (the 2nd level), etc. v(j)=k if node j is in the 11% kth level, where the shortest path (in terms of # of edges) from s to j has 12% length k+1. The source node s defaults to 1. 13 14% SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. 15% SPDX-License-Identifier: Apache-2.0 16 17[m n] = size (A) ; 18if (m ~= n) 19 error ('A must be square') ; 20end 21n = size (A,1) ; 22v = zeros (n,1) ; 23 24if (nargin < 2) 25 s = 1 ; 26end 27 28% ensure A is binary, and transpose it 29AT = spones (A') ; 30 31q = zeros (n,1) ; 32q (s) = 1 ; % q is the current level 33 34for level = 1:n 35 36 % assign the level to all nodes in q 37 v (q ~= 0) = level ; 38 39 % find all neighbors of q, as a binary vector 40 qnew = spones (AT * q) ; 41 42 % discard nodes in qnew that are already seen 43 qnew (v ~= 0) = 0 ; 44 45 % move to the new level 46 q = qnew ; 47 48 % stop if the new level is empty 49 if (~any (q)) 50 break ; 51 end 52 53end 54 55