억만년만에 코테문제를 풀었다.
오랜만에 푸는 것인만큼 쉬운 문제를 골라서 풀었음.
https://www.codetree.ai/missions/2/problems/graph-traversal/description
코드트리 | 코딩테스트 준비를 위한 알고리즘 정석
국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.
www.codetree.ai
난이도
- 하
- 나중에 긴가민가 할 때 코드 한번 다시 보는 정도면 충분
배운 점 + 실수한 점
- 그래프 탐색을 할 수 있는 방법에는 2가지가 있다는 것
1. 2차원 배열 활용
2. 인접리스트 활용(1차원 배열 각각에 ArrayList 달아둔거임) - arraylist의 메서드를 활용할 때, []가 아니라 ()라는 점(계속 get[]으로 쓰려고 해서 컴파일 오류가 났다)
import java.util.*;
public class Main {
static int n;
static int m;
static ArrayList<Integer>[] graph;
static boolean[] visited;
static int vertexNum = 0;
public static void DFS(int vertex){
for(int i = 0; i<graph[vertex].size(); i++){
int currV = graph[vertex].get(i);
if(!visited[currV]){
vertexNum++;
visited[currV] = true;
DFS(currV);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
graph = new ArrayList[n+1];
visited = new boolean[n+1];
visited[1] = true;
for(int i = 0; i<n+1; i++){
graph[i] = new ArrayList<Integer>();
}
for(int i = 0; i<m; i++){
int start = sc.nextInt();
int end = sc.nextInt();
graph[start].add(end);
graph[end].add(start);
}
DFS(1);
System.out.println(vertexNum);
}
}
'코딩테스트 > 매일 한 문제' 카테고리의 다른 글
[2024.11.04] BFS 탐색 / 갈 수 있는 곳들 (0) | 2024.11.04 |
---|---|
[2024.10.31(목)] 코드트리 : DFS/뿌요뿌요 (0) | 2024.10.31 |
[2024.10.31(목)] 코드트리 : DFS/안전지대 (0) | 2024.10.31 |
[2024.10.31(목)] 코드트리 : DFS/마을 구분하기 (1) | 2024.10.31 |
[2024.10.30(수)] 코드트리 : DFS/두 방향 탈출 가능 여부 판별하기 (0) | 2024.10.30 |
댓글