본문 바로가기

알고리즘/BFS|DFS6

[Sofreer 문제풀이] Lv.3(순서대로 방문하기) feat. Java DFS로 구현하는 건 어렵지 않았는데 문제 조건에서 방문해야 하는 특정 지점을 순서대로 방문해야한다는 부분 구현이 빠져있어서 시간이 좀 걸렸다. if(x == startend[index][0] && y == startend[index][1]){// 모두 다 거치고, 마지막에 도달했다면 if(index == m-1){ cnt++; return; } index++; } 이 부분에서 index는 방문해야하는 지점을 담은 startend를 도는 인덱스이고, index == m-1, 즉 마지막까지 방문했을 때 return하는 식으로 구현해야 한다. import java.io.*; import java.util.*; public class Main { static int n; static int m; static .. 2024. 4. 3.
[프로그래머스 연습문제 level_3 ] 단어 변환 bfs 로 풀었다. import java.util.*; class Solution { public int solution(String begin, String target, String[] words) { int answer = 0; if(!Arrays.asList(words).contains(target)){ return 0; } Queue myQueue = new LinkedList(); int[] visited = new int[words.length]; for ( int i = 0; i < words.length; i++ ) { if ( isChangeable(begin, words[i]) ) { myQueue.add(words[i]); visited[i] = 1; } } while(!myQueu.. 2023. 12. 7.
[프로그래머스 연습문제 level_2 ] 게임 맵 최단거리 import java.util.*; class Solution { static int[][] D = {{-1,0},{1,0},{0,-1},{0,1}}; static int N, M; static class Point{ int row, col, dist; Point(int r, int c, int d){ row = r; col = c; dist = d; } } public int solution(int[][] maps) { int answer = 0; N = maps.length; M = maps[0].length; answer = bfs(maps, 0,0,N,M); return answer; } static int bfs(int[][] maps, int sRow, int sCol, int eRow, in.. 2023. 11. 29.
[프로그래머스 연습문제 level_3 ] 네트워크 처음 생각 무조건 dfs 다. 내가 푼 방법 class Solution { static int[] visited; static int N = 0; static int[][] Computers; public int solution(int n, int[][] computers) { int answer = 0; visited = new int[n]; Computers = computers; N = n; for(int i=0; i 2023. 11. 16.
[알고리즘] DFS - 재귀호출, 스택(Stack) 1. 재귀호출 사용 import java.util.*; public class Main { static final int Max_N = 10; static int N, E; static int[][] Graph = new int [Max_N][Max_N]; // 노드,간선 정보를 이중배열에 담아둠 static boolean[] Visited = new boolean[Max_N]; // 노드 방문 여부를 확인하기위함 public static void main(String[] args){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLi.. 2023. 11. 3.
[Sofreer 문제풀이] Lv.2(장애물 인식 프로그램) feat. Java 1. 장애물 인식 프로그램 import java.io.*; import java.util.*; public class Main { static class Point{ int row, col; Point(int r, int c){ row = r; col = c; } } static int[][] D = {{-1,0},{1,0},{0,-1},{0,1}}; // 행/열 위,아래,왼,오 static int N; static int[][] board; static int cntBlock = 0; static ArrayList arrCnt = new ArrayList(); static int blockNum; static boolean[][] visited; // dfs 함수 static void dfs(int r.. 2023. 11. 2.