Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 알고리즘
- 백준
- 프로젝트 후기
- 리액트
- SBS 개발
- 사내시스템
- CompositionAPI
- react
- 자바
- 웹 개발 면접 질문
- MySQL
- 면접
- 뷰 리액트
- 백준알고리즘
- SBS 본사
- IT시스템개발
- 뷰
- URL입력
- 오라클
- 1차면접
- 경력직
- 트리
- Vue.js
- 첫 리액트
- 뷰 리액트 비교
- 쟈스
- 대문자
- e-HR
- 간단 프로젝트
- 첫 React
Archives
- Today
- Total
리주의 프로그래밍 공부
[2606] 바이러스 본문
간단한 bfs/dfs 문제
컴퓨터의 연결 관계를 2차원배열로 선언하고, 양방향 관계인 것을 고려하면 쉽게 풀 수 있다.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
// 지나온 곳 체크하기 위한 변수
public static int[] checked;
// 컴퓨터 네트워크 관계 저장 변수
public static int[][] rel;
//dfs를 위한 결과값 변수
public static int cnt = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int com = sc.nextInt();
checked = new int[com + 1];
rel = new int[com + 1][com + 1];
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
// 양방향 관계를 위해 다음과 같이 저장
rel[x][y] = 1;
rel[y][x] = 1;
}
// System.out.println(bfs());
dfs(1);
System.out.println(cnt);
}
public static int bfs() {
int result = 0;
Queue<Integer> q = new LinkedList<>();
q.add(1);
checked[1] = 1;
while (!q.isEmpty()) {
int now = q.poll();
for (int i = 2; i < checked.length; i++) {
if (rel[now][i] == 1 && checked[i] != 1) {
checked[i] = 1;
result++;
q.add(i);
}
}
}
return result;
}
public static void dfs(int a) {
checked[a] = 1;
for (int i = 1; i < checked.length; i++) {
if (rel[a][i] == 1 && checked[i] != 1) {
cnt++;
dfs(i);
}
}
}
}
'알고리즘 공부(백준)' 카테고리의 다른 글
[15651] N과 M (3) (0) | 2021.03.18 |
---|---|
[9663] N-Queen (0) | 2021.03.18 |
[2293] 동전 1 (0) | 2021.01.04 |
[11286] 절댓값 힙 (0) | 2021.01.02 |
[11279] 최대 힙 (0) | 2021.01.02 |