Ex)
<hide/>
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
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<>();
static Set<Integer> set = new HashSet<Integer>();
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);
System.out.println(set.size());
}
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);
set.add(i);
// System.out.printf("%d에서 %d로 이동\n", currV, i );
}
}
}
}
}
Note) 입출력 예시
<hide/>
[입력]
7
6
1 2
2 3
1 5
5 2
5 6
4 7
[출력]
4
'자료구조와 알고리듬 With Java > [Study] BAEKJOON 프로그래머스 CodeUp LeetCode' 카테고리의 다른 글
BFS 마법의 비료 (0) | 2022.04.29 |
---|---|
Java 2차원 맵 탐색을 위한 BFS (0) | 2022.04.28 |
Java로 BFS 구현하기 (0) | 2022.04.28 |
Code up 4060 전광판 전구 조작 (0) | 2022.04.24 |
Code up 4572 영역 구하기 / 오류 수정하기 (0) | 2022.04.24 |