递归实现广度优先遍历:
package cn.itcast.demo;
/**
* 广度优先遍历可以用递归的解法吗?试把课程中解法改造为递归方式
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//广度优先遍历
public class WidthTravel {
static List lst = new ArrayList();
static Set tag = new HashSet();
public static void widthTravel(int[][]g,int k){
lst.add(k);
for(;;){
if(lst.isEmpty()) break;
int node = (Integer)lst.get(0);
System.out.println(node);
tag.add(node);
lst.remove(0);
for(int i=0; i<g[node].length; i++){
if(g[node][i]==1 && tag.contains(i)==false && lst.indexOf(i)<0) widthTravel(g,i);
}
}
}
public static void main(String[] args)
{
// 图的邻接表定义
int[][] g = {
{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}
};
//传递一个数组过去,而且是从0开始广度遍历;
widthTravel(g,0);
}
}
递归实现深度优先遍历:
public class MyA
{
public static void deepTravel(int[][] a, int[] color, int k)
{
System.out.println(k);
color[k] = 1;
//判断与k点相连的没有标示的点,递归
for(int i=0; i<a[k].length; i++){
if(a[k][i] == 1 && color[i]==0) deepTravel(a,color,i);
}
}
public static void main(String[] args)
{
//需要开一个数组,来记录染色信息
int[][] a = {
{0,1,1,1,0},
{1,0,1,1,1},
{1,1,0,0,0},
{1,1,0,0,0},
{0,1,0,0,0}
};
//定义一个颜色数组,它的长度为邻接矩阵的长度。它用来表示已经访问过的点
int[] color = new int[a.length];
//从0点开始访问
deepTravel(a, color, 0);
}
}