import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class BreadthTraversal
{
public static void main(String[] args)
{
int[][] a = {{0,1,1,0,0,0,0},{1,0,0,1,0,0,1},{1,0,0,0,0,1,1},{0,1,0,0,1,0,0},{0,0,0,1,0,1,1},{0,0,1,0,1,0,0},{0,1,1,0,1,0,0}};
List<Integer> list = new ArrayList<Integer>();
Set<Integer> set = new HashSet<Integer>();
list.add(0);
while(true)
{
if(list.isEmpty())
{
break;
}
int node = list.get(0);
System.out.println(node);
set.add(node);
list.remove(0);
for(int i = 0; i < a[node].length; i ++)
{
if(a[node][i] == 1 && !set.contains(i) && list.indexOf(i) < 0)
{
list.add(i);
}
}
}
}
//以下是递归方法
/×
public static void deepTravel(int[][] a, Set<Integer> set, List<Integer> list)
{
if(list.isEmpty())
{
return;
}
int node = list.get(0);
System.out.println(node);
set.add(node);
list.remove(0);
for(int i = 0; i < a[node].length; i ++)
{
if(a[node][i] == 1 && !set.contains(i) && list.indexOf(i) < 0)
{
list.add(i);
}
}
deepTravel(a, set, list);
}
×/
}