import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {

    static List<List<Integer>> g;

    static boolean[] visited;

    static void printVertex(int v) {
        System.out.println("visited " + v);
    }

    static void dfs(int v) {
        visited[v] = true; 
        printVertex(v);
        for (int u: g.get(v)) {
            if(!visited[u]) {
                dfs(u);
            }
        }
    }
    
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m=sc.nextInt(), s=sc.nextInt()-1;

        g = new ArrayList<List<Integer>>(n);

        for (int i = 0; i < n; i++) {
            g.add(new ArrayList<Integer>());
        }

        for (int i = 0; i < m; i++) {
            int a = sc.nextInt()-1, b = sc.nextInt()-1; 
            g.get(a).add(b);
            g.get(b).add(a);
        }

        visited = new boolean[n]; 

        dfs(s);

        sc.close();
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: