Skip to content
Open

kmj #15

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.DS_Store
92 changes: 92 additions & 0 deletions source/KMJ/bj1260.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@



## bj

```java
//package p1260; //error occurs

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class DFS_BFS {

//DFS 구현
public static void dfs(int start, LinkedList<Integer>[] adj, boolean[] visited) {
visited[start] = true;
System.out.print(start + " ");

Iterator<Integer> iter = adj[start].listIterator();
while (iter.hasNext()) {
int nextStart = iter.next();
if (!visited[nextStart]) {
dfs(nextStart, adj, visited);
}

}

}
//BFS 구현 - bfs는 queue(FIFO 형식)로 구현
public static void bfs(int start, LinkedList<Integer>[] adj, boolean[] visited) {

Queue<Integer> queue = new LinkedList<Integer>();
visited[start] = true;
queue.add(start); // queue에 값 넣기

while (queue.size() != 0) {
start = queue.poll(); // queue의 첫 번째 값 꺼내기
System.out.print(start + " ");

Iterator<Integer> iter = adj[start].listIterator();
while (iter.hasNext()) { // 인접한 정점 존재하면
int nextStart = iter.next();
if (!visited[nextStart]) {
visited[nextStart] = true;
queue.add(nextStart); // queue에 값 넣기
}
}
}
}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt(); // 정점 개수
int m = sc.nextInt(); // 간선 개수
int v = sc.nextInt(); // 시작 정점 번호

boolean[] visited = new boolean[n + 1]; // 방문 확인 배열

LinkedList<Integer>[] adjList = new LinkedList[n + 1]; // adjacent list로 표현

for (int i = 0; i <= n; i++) { //각 인접노드와 연결된 노드도 linked list로 정의
adjList[i] = new LinkedList<Integer>();
}

for (int i = 0; i < m; i++) { // 간선 입력 및 저장
int m1 = sc.nextInt();
int m2 = sc.nextInt();
adjList[m1].add(m2); // 양방향
adjList[m2].add(m1);
}

for (int i = 1; i <= n; i++) { // 정점 번호 오름차순 배치
Collections.sort(adjList[i]);
}

dfs(v, adjList, visited); // dfs 실행

for (int i = 0; i <= n; i++) { //array 초기화
visited[i] = false;
}

System.out.println();

bfs(v, adjList, visited); // bfs 실행
}
}
```