반응형
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
인접리스트로 구현해봄.
내 코드
메모리 : 18448 KB
시간 : 113 ms
코드길이 : 1842 B
[내 코드]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Solution {
static int N;
static int M;
static ArrayList<Integer>[] list;
static int result;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int T= Integer.parseInt(br.readLine());
for(int t = 1; t <= T; t++) {
sb.append('#').append(t).append(' ');
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
list = new ArrayList[N + 1];
boolean[] isVisited = new boolean[N + 1];
result = 0;
if(M == 0 || M == 1) {
sb.append(M + 1).append('\n');
continue;
}
//인접리스트 초기화** 필수
for(int n = 0; n < N + 1; n++) {
list[n] = new ArrayList<Integer>();
}
for(int m = 0; m < M; m++) {
st = new StringTokenizer(br.readLine());
int node1 = Integer.parseInt(st.nextToken());
int node2 = Integer.parseInt(st.nextToken());
list[node1].add(node2);
list[node2].add(node1);
}
for(int i = 1; i <= N; i++) {
isVisited[i] = true;
search(i, 1, isVisited);
isVisited[i] = false;
}
sb.append(result).append('\n');
}
System.out.print(sb);
}
public static void search(int node, int length, boolean[] isVisited) {
for(int i = 0; i < list[node].size(); i++) {
int nextNode = list[node].get(i);
if(!isVisited[nextNode]) {
isVisited[nextNode] = true;
search(nextNode, length + 1, isVisited);
isVisited[nextNode] = false;
}
}
result = Math.max(result, length);
}
}
반응형
'SSAFY > SWEA' 카테고리의 다른 글
[SWEA] 1873 : 상호의 배틀필드 (0) | 2023.05.01 |
---|---|
[SWEA] 6190 : 정곤이의 단조 증가하는 수 (0) | 2023.05.01 |
[SWEA] 2805 : 농작물 수확하기 (0) | 2023.04.30 |
[SWEA] 5215 : 햄버거 다이어트 (0) | 2023.04.30 |
[SWEA] 1486 : 장훈이의 높은 선반 (0) | 2023.04.29 |