on
[java 백준] 실버 2/ 1260번 DFS와BFS
[java 백준] 실버 2/ 1260번 DFS와BFS
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util. Scanner ;
public class Main {
static int node[][]; // 인접행렬
static int check[]; // 노드의 방문표시
static Queue < Integer > queue = new LinkedList < > ();
public static void dfs( int start) {
if (check[start] = = 1 ) {
return ;
} else {
check[start] = 1 ; // sean 채워주기
}
System . out . print (start + " " );
for ( int i = 1 ; i < node. length ; i + + ) {
if (node[start][i] = = 1 ) {
dfs(i);
}
}
}
public static void bfs( int start) {
queue.offer(start);
check[start] = 1 ;
while ( ! queue.isEmpty()) {
int x = queue.remove();
System . out . print (x + " " );
for ( int i = 1 ; i < node. length ; i + + ) {
if (check[i] ! = 1 & & node[x][i] = = 1 ) {
queue.offer(i);
check[i] = 1 ;
}
}
}
}
public static void main( String [] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner ( System . in );
int n = sc.nextInt(); // 정점의 개수
int m = sc.nextInt(); // 간선의 개수
int start = sc.nextInt(); // 탐색 시작
node = new int [n + 1 ][n + 1 ];
check = new int [n + 1 ];
for ( int i = 0 ; i < m; i + + ) { // 인접행렬
int a = sc.nextInt();
int b = sc.nextInt();
node[a][b] = 1 ;
node[b][a] = 1 ;
}
dfs(start);
Arrays.fill(check, 0 );
System . out . println ( "" );
bfs(start);
}
}
from http://we1cometomeanings.tistory.com/152 by ccl(A) rewrite - 2021-09-23 00:26:18