dfs를 호출 할 때 매개변수..?
해결됨
[자바/Java] 문과생도 이해하는 DFS 알고리즘! - 입문편
안녕하세요! 강의 넘 잘 듣고 있습니다. 하루만에 거의 다들었네요,,ㅋㅋ 질문이 있습니다 혹시 dfs를 호출할 때 이런 '-'나 '|' 같은게 나오면 매개변수로 '-' 나 '|' 를 추가해서 dfs함수에 넘겨도 되는건가요? 저는 이렇게 할 때가 많은데 이렇게 하지 않고 오히려 dfs 함수 안에서 해결해주는 게 더 간단한 것 같기도 해서요.. 보통은 어떻게 하시나요? 전 4방 탐색을 하면서 이렇게 풀었었네요,, 한 방향만 탐색하는 팁 배워갑니다 ㅎㅎ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int[] dr = {-1, 1, 0, 0}; static int[] dc = {0, 0, -1, 1}; static int N, M; static char[][] arr; static int ans; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); arr = new char[N+2][M+2]; for (int i = 1; i <= N; i++) { String str = br.readLine(); for (int j = 1; j <= M; j++) { arr[i][j] = str.charAt(j-1); } } for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (arr[i][j] == '|') { dfs(i, j, '|'); ans++; } else if (arr[i][j] == '-'){ dfs(i, j, '-'); ans++; } } } System.out.println(ans); } private static void dfs(int r, int c, char shape) { int start = 0; int end = 0; if (shape == '|') { start = 0; end = 1; } else if (shape == '-'){ start = 2; end = 3; } arr[r][c] = '1'; for (int d = start; d <= end; d++) { int nr = r + dr[d]; int nc = c + dc[d]; if(arr[nr][nc] == shape) { arr[nr][nc] = '1'; dfs(nr, nc, shape); } } } }
- java
- 코딩-테스트
- 알고리즘
- 매개변수





