티스토리 뷰
반응형
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package BACKJOON; | |
import java.io.*; | |
import java.util.*; | |
public class back_1260 { | |
static int[][] arr; | |
static boolean[] visit; | |
static int N; | |
static int M; | |
static int V; | |
public static void main(String[] args) throws IOException { | |
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); | |
StringTokenizer st = new StringTokenizer(br1.readLine()); | |
N = Integer.parseInt(st.nextToken()); //node | |
M = Integer.parseInt(st.nextToken()); // edge | |
V = Integer.parseInt(st.nextToken()); //start | |
arr = new int[1001][1001]; | |
visit = new boolean[1001]; | |
for (int i = 0; i < M; i++) { | |
Scanner sc = new Scanner(System.in); | |
int x = sc.nextInt(); | |
int y = sc.nextInt(); | |
arr[x][y] = arr[y][x]=1; | |
} | |
dfs(V); | |
visit = new boolean[1001]; | |
System.out.println(); | |
bfs(); | |
} | |
public static void dfs(int V) { | |
visit[V] = true; | |
System.out.print(V + " "); | |
for(int i=1; i<=N; i++){ | |
if(arr[V][i] ==1 && visit[i]== false){ | |
dfs(i); | |
} | |
} | |
} | |
public static void bfs() { | |
Queue<Integer> queue = new LinkedList<>(); | |
queue.offer(V); | |
visit[V] = true; | |
System.out.print(V + " "); | |
while(!queue.isEmpty()){ | |
int temp = queue.poll(); | |
for(int i=1; i<=N; i++){ | |
if(arr[temp][i]==1 && visit[i]==false){ | |
queue.offer(i); | |
visit[i]=true; | |
System.out.print(i + " "); | |
} | |
} | |
} | |
} | |
} |

반응형
'알고리즘 > 백준' 카테고리의 다른 글
15649번 백준 (0) | 2021.04.20 |
---|---|
백준 9251 (0) | 2021.04.20 |
[back_11404] (0) | 2021.03.29 |
[1197]최소 스패닝 트리(MST) / 스패닝 트리(STP) (0) | 2021.02.14 |
[백준] 1330번 두 수 비교하기 (0) | 2021.02.09 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 릿코드
- springboot
- java
- spring-cloud
- 매트랩
- 디자인패턴
- security
- 알고리즘
- nginx
- Solid
- 스프링부트
- 면접
- 스프링
- 그래프
- interview
- 백준
- Algorithm
- 수학
- ajax
- C언어
- 프로그래머스
- JPA
- 자바
- CS
- 자격증
- kakao
- Matlab
- docker
- OOP
- Spring
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함