코딩테스트/SWEA
[SWEA 2814번] 최장경로
seung_ho_choi.s
2025. 5. 8. 23:54
728x90
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.io.*;
import java.util.*;
public class Solution {
static int N;
static int M;
static int[][] graph;
static int cnt;
static int result;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
for (int test = 1; test <= T; test++) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
graph = new int[N + 1][N + 1];
visit = new boolean[N + 1];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int fNode = Integer.parseInt(st.nextToken());
int bNode = Integer.parseInt(st.nextToken());
graph[fNode][bNode] = bNode;
graph[bNode][fNode] = fNode;
}
result = 1;
cnt = 1;
for (int i = 1; i < N + 1; i++) {
dfs(i);
}
System.out.println("#" + test + " " + result);
}
}
private static void dfs(int currentNode) {
if (cnt == N) {
return;
}
for (int i = 1; i < N + 1; i++) {
if (currentNode == i) {
continue;
}
if (graph[currentNode][i] != 0 && !visit[i]) {
visit[currentNode] = true;
cnt++;
result = Math.max(result, cnt);
dfs(i);
cnt--;
visit[currentNode] = false;
}
}
}
}
어제 다이스트라 복습 문제 풀어서 오늘 이 문제 풀고 다이스트라 처럼 접근하다가 실수 엄청했다...
가장 기본적인 DFS 문제인데 뭐한거지??? ㅋㅋ
핵심은 visit boolean 배열과 재귀함수를 이용해서 풀면 된다.
728x90