728x90
DFS와 BFS의 가장 기본적인 문제를 통해 구현해보고 눈에 익히고자 기록해본다.
https://www.acmicpc.net/problem/1260
// BFS 시작
private static void Bfs(int v) {
visited[v] = true;
queue.add(v); // BFS는 Queue를 활용!
while (!queue.isEmpty()) { // Point!
int x = queue.poll();
BFSsb.append(x+" ");
for (int i = 1; i <= N; i++) {
if (!visited[i] && arr[x][i] == 1) {
visited[i]=true;
queue.add(i);
}
}
}
}
// DFS시작
private static void Dfs(int i) {
visited[i] = true;
DFSsb.append(i+" ");
for (int j = 1; j <= N; j++) {
if(!visited[j]&&arr[i][j]==1) {
Dfs(j); // DFS는 재귀를 활용!
}
}
}
728x90
'Algorithm' 카테고리의 다른 글
[Algorithm - DFS/BFS] BFS문제 풀기 ++ 응용(7576번, 1697번) (0) | 2024.04.29 |
---|---|
[백준-1012번] 유기농 배추 (1) | 2024.01.24 |