회원가입
로그인
Toggle navigation
문제
문제
전체 문제
문제 출처
단계별로 풀어보기
알고리즘 분류
추가된 문제
문제 순위
문제
푼 사람이 한 명인 문제
아무도 못 푼 문제
최근 제출된 문제
최근 풀린 문제
랜덤
출처
ICPC
Olympiad
한국정보올림피아드
한국정보올림피아드시․도지역본선
전국 대학생 프로그래밍 대회 동아리 연합
대학교 대회
카카오 코드 페스티벌
Coder's High
ICPC
Regionals
World Finals
Korea Regional
Africa and the Middle East Regionals
Europe Regionals
Latin America Regionals
North America Regionals
South Pacific Regionals
문제집
대회
1
채점 현황
랭킹
게시판
그룹
더 보기
재채점 기록
블로그
강의
실험실
도움말
BOJ Stack
BOJ Book
전체
공지
자유
질문
오타/오역/요청
게시판 공지
홍보
업데이트
solved.ac
글쓰기
질문 도움말
자주묻는 질문
어디서 틀리는지 못찾겠습니다.
1260번 - DFS와 BFS
jjjhhh14
2년 전
0
제출 시 계속 틀리는데, 틀리는 위치를 못찾겠습니다.
public class Main{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] NMV = getIntArr(br.readLine()); Graph dfs = new Graph(); Graph bfs = new Graph(); for (int i=0; i<NMV[1]; i++){ int[] nodes = getIntArr(br.readLine()); dfs.addEdge(nodes[0], nodes[1]); bfs.addEdge(nodes[0], nodes[1]); } dfs.dfs(dfs.nodes.get(NMV[2])); System.out.println(); bfs.bfs(bfs.nodes.get(NMV[2])); } private static int[] getIntArr(String input) { return Arrays.stream(input.split(" ")) .mapToInt(Integer::parseInt).toArray(); } static class Node implements Comparable<Node>{ int data; List<Node> adjacent = new LinkedList<>(); boolean visited; Node(int data){ this.data = data; } @Override public int compareTo(Node o) { return this.data-o.data; } } static class Graph{ HashMap<Integer, Node> nodes = new HashMap<>(); public void addEdge(int a1, int a2){ Node n1 = addNode(a1); Node n2 = addNode(a2); if (!n1.adjacent.contains(n2)){ n1.adjacent.add(n2); } if (!n2.adjacent.contains(n1)){ n2.adjacent.add(n1); } } private Node addNode(int data) { if (nodes.get(data)==null){ Node newNode = new Node(data); nodes.put(data, newNode); } return nodes.get(data); } public void dfs(Node node){ if (node==null || node.visited){ return; } node.visited = true; System.out.print(node.data + " "); Collections.sort(node.adjacent); for (Node adjacent: node.adjacent){ if (!adjacent.visited){ dfs(adjacent); } } } public void bfs(Node node){ Queue<Node> queue = new LinkedList<>(); queue.add(node); node.visited = true; while (!queue.isEmpty()){ Node n = queue.poll(); Collections.sort(node.adjacent); for (Node adjacent: n.adjacent){ if (!adjacent.visited){ adjacent.visited = true; queue.add(adjacent); } } System.out.print(n.data + " "); } } } }
댓글을 작성하려면
로그인
해야 합니다.
jjjhhh14 2년 전
제출 시 계속 틀리는데, 틀리는 위치를 못찾겠습니다.