diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/source/KMJ/bj1260.md b/source/KMJ/bj1260.md new file mode 100644 index 0000000..51167c3 --- /dev/null +++ b/source/KMJ/bj1260.md @@ -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[] adj, boolean[] visited) { + visited[start] = true; + System.out.print(start + " "); + + Iterator 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[] adj, boolean[] visited) { + + Queue queue = new LinkedList(); + visited[start] = true; + queue.add(start); // queue에 값 넣기 + + while (queue.size() != 0) { + start = queue.poll(); // queue의 첫 번째 값 꺼내기 + System.out.print(start + " "); + + Iterator 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[] adjList = new LinkedList[n + 1]; // adjacent list로 표현 + + for (int i = 0; i <= n; i++) { //각 인접노드와 연결된 노드도 linked list로 정의 + adjList[i] = new LinkedList(); + } + + 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 실행 + } +} +```