SDUT 2107 图的深度遍历

点击打开题目链接

#include <bits/stdc++.h>
using namespace std;

bool vis[100];
int n, k, m, u, v;
int Graph[100][100];
void DFS(int s);

int main()
{
    cin >> k;
    while(k --)
    {
        memset(Graph, 0, sizeof(Graph));
        memset(vis, 0, sizeof(vis));
        cin >> n >> m;
        while(m --)
        {
            cin >> u >> v;
            Graph[u][v] = Graph[v][u] = 1;
        }
        cout << Graph[0][0];
        vis[0] = 1;
        DFS(0);
        cout  << endl;
    }
    return 0;
}

void DFS(int s)
{
  for(int i = 0; i < n; i++)
  {
      if(!vis[i] && Graph[s][i])
      {
          vis[i] = 1;
          cout << ' ' << i;
          DFS(i);
      }
  }
}

import java.util.Scanner;

public class Main {
	private static Scanner cin = new Scanner(System.in);
	private static boolean visited[];
	private static boolean Edge[][];
	private static int n, m, k;
	public static void main(String[] args) {
			n = cin.nextInt();
		    while(n>0)
		    {
		        Edge = null;
		        Edge =  new boolean[1010][1010];
		        visited = null;
		        visited = new boolean[1010];
		        k=cin.nextInt();
		        m=cin.nextInt();
		        while(m > 0)
		        {
		            int v, u;
		            u = cin.nextInt();
		            v = cin.nextInt();
		            Edge[u][v] = Edge[v][u] = true;
		            m--;
		        }
		        System.out.print(0);
		        DFS(Edge,0);
		        System.out.println();
		        n--;
		    }
	}
	public static boolean DFS(boolean Edge[][],int st){
        	visited[st] = true;
            for(int i = 0; i < k; i++)
            {
                if(!visited[i] && Edge[st][i])
                {
                    System.out.print(" " + i);
                    visited[i] = true;
                    DFS(Edge,i);
                }
            }
        return true;
	}
}

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