DFS+BFS
import java. util. *;
class Graph {
public int [ ] [ ] adjacencyMatrix;
public int arcNumber;
public int vertexNumber;
public boolean [ ] visited;
public void createGraph ( ) {
Scanner scan = new Scanner ( System. in) ;
System. out. print ( "请输入图的顶点数:" ) ;
this . vertexNumber = scan. nextInt ( ) ;
System. out. print ( "请输入图的边数:" ) ;
this . arcNumber = scan. nextInt ( ) ;
this . adjacencyMatrix = new int [ vertexNumber] [ vertexNumber] ;
this . visited = new boolean [ vertexNumber] ;
for ( int i = 0 ; i < vertexNumber; i++ ) {
for ( int j = 0 ; j < vertexNumber; j++ ) {
adjacencyMatrix[ i] [ j] = 0 ;
}
}
System. out. println ( "各条边如下(顶点+空格+顶点):" ) ;
for ( int i = 0 ; i < arcNumber; i++ ) {
int v1 = scan. nextInt ( ) ;
int v2 = scan. nextInt ( ) ;
adjacencyMatrix[ v1- 1 ] [ v2- 1 ] = adjacencyMatrix[ v2- 1 ] [ v1- 1 ] = 1 ;
}
}
public void init ( ) {
for ( int i = 0 ; i < vertexNumber; i++ ) {
visited[ i] = false ;
}
}
public void dfs ( int v) {
if ( visited[ v] == false ) {
System. out. print ( ( v+ 1 ) + " " ) ;
visited[ v] = true ;
}
for ( int i = 0 ; i < vertexNumber; i++ ) {
if ( visited[ i] == false && adjacencyMatrix[ i] [ v] == 1 ) {
dfs ( i) ;
}
}
}
public void bfs ( int v) {
ArrayDeque< Integer> queue = new ArrayDeque < Integer> ( ) ;
if ( visited[ v] == false ) {
System. out. print ( ( v+ 1 ) + " " ) ;
visited[ v] = true ;
queue. add ( v) ;
}
while ( queue. isEmpty ( ) == false ) {
int front = queue. remove ( ) ;
for ( int i = 0 ; i < vertexNumber; i++ ) {
if ( adjacencyMatrix[ front] [ i] == 1 && visited[ i] == false ) {
queue. add ( i) ;
visited[ i] = true ;
System. out. print ( ( i+ 1 ) + " " ) ;
}
}
}
System. out. println ( ) ;
}
}
public class Main {
public static void main ( String[ ] args) {
Graph graph = new Graph ( ) ;
graph. createGraph ( ) ;
graph. init ( ) ;
graph. dfs ( 0 ) ;
System. out. println ( ) ;
graph. init ( ) ;
graph. bfs ( 0 ) ;
}
}