-
자바 DFS, BFS 이론, 구현, 활용컴퓨터 공부/JAVA 2020. 5. 24. 16:38
baaaaaaaaaaaaaaaaaaaaaaarkingdog.tistory.com/729
[실전 알고리즘] 0x05강 - BFS, DFS_구버전
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 현재 보고있는 강..
blog.encrypted.gg
매우 이해하기 쉽게 정리해주신..!!
BFS는 큐로 구현, DFS는 스택/ 재귀함수
BFS : 깊게 깊게 -> 처음 넣은 거 먼저 탐색하는 큐
DFS : 넓게 넓게 -> 마지막에 넣은 거 먼저 탐색하는 스택
//재귀적 dfs public static void dfs(int i) { checked[i] = true; //먼저 방문했다고 표시 System.out.print(i + " "); for(int j = 1; j <= n; j++) { if(check[i][j] == 1 && checked[j] == false) { //이어져있고 방문 안한 곳 dfs(j); } } }
//큐로 bfs 구현 public static void bfs() { Queue<Integer> queue = new LinkedList<Integer>(); ///큐 queue.offer(start); //시작점도 Queue에 넣어야 함 checked[start] = true; //방문 표시 System.out.print(start + " "); //Queue가 빌 때까지 반복. 방문 정점은 확인, 출력 후 Queue에 넣어 순서대로 확인 while(!queue.isEmpty()) { int temp = queue.poll(); for(int j = 1; j <= n; j++) { if(check[temp][j] == 1 && checked[j] == false) { //이어져있고 방문 안한 곳 queue.offer(j); //큐에 넣고 checked[j] = true; //방문 표시 System.out.print(j + " "); } } }
dfs 이용해서 나올수 있는 값 구하기 -> jjjayyy.tistory.com/87
[프로그래머스] 알고리즘 연습 문제 : 타겟 넘버 (자바/JAVA)
https://programmers.co.kr/learn/courses/30/lessons/43165?language=java 코딩테스트 연습 - 타겟 넘버 | 프로그래머스 n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고..
jjjayyy.tistory.com
class Solution { public int solution(int[] numbers, int target) { int answer = 0; answer = dfs(numbers, 0, 0, target); return answer; } int dfs(int[] numbers, int n, int sum, int target) { if(n == numbers.length) { if(sum == target) { return 1; } return 0; } return dfs(numbers, n + 1, sum + numbers[n], target) + dfs(numbers, n + 1, sum - numbers[n], target); } }
[프로그래머스 - 코딩테스트 연습] 깊이/너비 우선 탐색 (DFS/BFS) (1)
cocojelly.github.io
가장 많이 나오는 문제!!!
섬/ 바다 구분하기
class Solution { public int solution(int n, int[][] computers) { int answer = 0; boolean[] chk = new boolean[n]; for(int i = 0; i < n; i++) { if(!chk[i]) { dfs(computers, chk, i); //dfs 탐색 기준점 달라짐 -> 새로운 섬 answer++; //기준점이 달라질 때마다 증가 } } return answer; } void dfs(int[][] computers, boolean[] chk, int start) { chk[start] = true; for(int i = 0; i < computers.length; i++) { if(computers[start][i] == 1 && !chk[i]) { dfs(computers, chk, i); } } } }
'컴퓨터 공부 > JAVA' 카테고리의 다른 글
해시맵 사용시 유용한 메서드, 기능, 정렬 (0) 2020.05.23 문자열 자르기 (0) 2020.05.23 오름차순, 내림차순 정렬 관련 문제 풀 때! (0) 2020.05.23 int[] <-> ArrayList, String[] <=> ArrayList 변환 (0) 2020.05.23 소수인지 판별법 (0) 2020.05.23