图的遍历(广度和深度)
来源:互联网 发布:华为mate9数据恢复 编辑:程序博客网 时间:2024/06/10 04:19
- class Graph1 {
- protected int n;
- protected int mat[][];
- protected int visited[];
- public Graph1(int m1[][]){
- n = m1.length;
- mat = new int [n][n];
- System.arraycopy(m1, 0, mat, 0, n);
- visited= new int [n];
- }
- public Graph1(){
- }
- public void depthFirstSearch(){
- System.out.println("深度优先遍历Depth first search:");
- for(int k=1;k<=n;k++){
- depthfs(k);
- System.out.println();
- unvisited();
- }
- }
- private void unvisited() {
- int i;
- for(i = 0;i<visited.length;i++){
- visited[i]=0;
- }
- }
- private void depthfs(int k) {
- int i,j=0;
- System.out.print(" v"+k+"->");
- i = k - 1;
- visited[i]=1;
- while(j<n){
- if(mat[i][j]==1 && visited[j]==0){
- depthfs(j+1);
- }else {
- j++;
- }
- }
- }
- }
- public class testGraph1{
- public static void main(String ag[]){
- int mat[][]= {{0,1,0,0},{0,0,1,1},{0,0,0,0},{1,0,1,0}};
- Graph1 g1 = new Graph1(mat);
- g1.depthFirstSearch();
- }
- }