Java图的广度遍历 邻接矩阵

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);

}

×/

}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/cgguopengfei/article/details/52840814
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞