Ex)
<hide/>
package first;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFSpractice0 {
static int MAX_COUNT = 101;
static int [][] AdjMatrix = new int [MAX_COUNT][MAX_COUNT];
static int[] VisitMatrix = new int[MAX_COUNT];
static int VertaxCount, EdgeCount;
static Queue<Integer> queue = new LinkedList<>();
public static void main(String[] args) {
int StartV = 1;
Scanner scan = new Scanner(System.in);
VertaxCount = scan.nextInt();
EdgeCount = scan.nextInt();
for(int i = 0 ; i< EdgeCount; ++i) {
int V1 = scan.nextInt();
int V2 = scan.nextInt();
AdjMatrix[V1][V2] = 1;
AdjMatrix[V2][V1] = 1;
}
BFSmethod(StartV);
}
public static void BFSmethod(int _StartVertax) {
VisitMatrix[_StartVertax] = 1;
queue.add(_StartVertax);
System.out.printf("%d에서 시작\n", _StartVertax);
while(false == queue.isEmpty()) {
int currV = queue.poll();
for(int i = 1; i <= VertaxCount ;++i) {
if(0 == VisitMatrix[i] && 1 == AdjMatrix[currV][i]) {
VisitMatrix[currV] = 1;
queue.add(i);
System.out.printf("%d에서 %d로 이동\n", currV, i );
}
}
}
}
}
Note) 입출력 예시
<hide/>
[입력]
4 4
1 2
1 3
2 4
3 4
[출력]
1에서 시작
1에서 2(으)로 이동
1에서 3(으)로 이동
2에서 4(으)로 이동
3에서 4(으)로 이동
[입력]
6 9
1 2
1 3
2 4
2 5
3 4
3 6
4 5
4 6
5 6
[출력]
1에서 시작
1에서 2(으)로 이동
1에서 3(으)로 이동
2에서 4(으)로 이동
2에서 5(으)로 이동
3에서 4(으)로 이동
3에서 6(으)로 이동
4에서 5(으)로 이동
4에서 6(으)로 이동
5에서 6(으)로 이동
4에서 6(으)로 이동
5에서 6(으)로 이동
'자료구조와 알고리듬 With Java > [Study] BAEKJOON 프로그래머스 CodeUp LeetCode' 카테고리의 다른 글
Java 2차원 맵 탐색을 위한 BFS (0) | 2022.04.28 |
---|---|
Code up 4503 바이러스 (BFS) (0) | 2022.04.28 |
Code up 4060 전광판 전구 조작 (0) | 2022.04.24 |
Code up 4572 영역 구하기 / 오류 수정하기 (0) | 2022.04.24 |
Code up 4714 BAEKJOON 2458 키 순서 (0) | 2022.04.24 |