250x250
Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 막내의막무가내 알고리즘
- 막내의막무가내 플러터 flutter
- 막내의막무가내 프로그래밍
- 부스트코스
- 막내의막무가내 안드로이드 코틀린
- Fragment
- 막내의막무가내 코틀린 안드로이드
- 막내의막무가내 목표 및 회고
- 부스트코스에이스
- 막내의막무가내 일상
- 막내의 막무가내
- 막무가내
- 막내의막무가내 rxjava
- 막내의 막무가내 알고리즘
- 안드로이드
- 주택가 잠실새내
- 막내의막무가내 안드로이드
- 2022년 6월 일상
- 안드로이드 sunflower
- 막내의막무가내 안드로이드 에러 해결
- 안드로이드 Sunflower 스터디
- 주엽역 생활맥주
- flutter network call
- 막내의막무가내 플러터
- 프로그래머스 알고리즘
- 프래그먼트
- 막내의막무가내 SQL
- 막내의막무가내 코틀린
- 막내의막무가내 코볼 COBOL
- 막내의막무가내
Archives
- Today
- Total
막내의 막무가내 프로그래밍 & 일상
[알고리즘] 프로그래머스 네트워크 -dfs, bfs- 본문
728x90
https://programmers.co.kr/learn/courses/30/lessons/43162?language=kotlin
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있��
programmers.co.kr
BFS 를 사용하여 처음 연결된 곳이 생길 경우 총 네트워크 개수의 -1 을 해주어 해결했습니다. ㅎㅎ
풀이방법은 다음과 같습니다.
[Java]
class Solution {
private static int[][] map;
private static boolean[] isVisited;
private static int n;
private static int answer = 0;
private static void dfs(int start) {
if (isVisited[start]) {
return;
}
isVisited[start] = true;
for (int j = 0; j < n; j++) {
if (map[start][j] == 1 && isVisited[j] == false) {
dfs(j);
answer--; // 붙어 있는거면 전체 네트워크 개수 - 1
}
}
}
public int solution(int n, int[][] computers) {
Solution.n = n;
map = new int[n][n];
isVisited = new boolean[n];
answer = n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = computers[i][j];
}
}
for (int i = 0; i < n; i++) {
dfs(i);
}
System.out.println(answer);
return answer;
}
}
[Kotlin]
internal class Solution {
fun solution(n: Int, computers: Array<IntArray>): Int {
Solution.n = n
map = Array(n) { IntArray(n) }
isVisited = BooleanArray(n)
answer = n
for (i in 0 until n) {
for (j in 0 until n) {
map[i][j] = computers[i][j]
}
}
for (i in 0 until n) {
dfs(i)
}
return answer
}
companion object {
private lateinit var map: Array<IntArray>
private lateinit var isVisited: BooleanArray
private var n: Int = 0
private var answer = 0
private fun dfs(start: Int) {
if (isVisited[start]) {
return
}
isVisited[start] = true
for (j in 0 until n) {
if (map[start][j] == 1 && isVisited[j] == false) {
dfs(j)
answer-- // 붙어 있는거면 전체 네트워크 개수 - 1
}
}
}
}
}
mtjin/algorithm_practice
알고리즘 문제풀이 연습. Contribute to mtjin/algorithm_practice development by creating an account on GitHub.
github.com
댓글과 공감은 큰 힘이 됩니다. 감사합니다!!
728x90
'알고리즘 > DFS, BFS, 시뮬, 백트래킹' 카테고리의 다른 글
[알고리즘] 프로그래머스 여행경로 (java) -bfs, dfs- (0) | 2020.06.02 |
---|---|
[알고리즘] 프로그래머스 단어 변환 -dfs, bfs- (0) | 2020.05.31 |
[알고리즘] 프로그래머스 방문 길이 -Summer/Winter Coding(~2018)- (선을 방문하는 문제) (0) | 2020.05.18 |
[알고리즘] 프로그래머스 타겟 넘버 -깊이/너비 우선 탐색(DFS/BFS)- (0) | 2020.05.16 |
[알고리즘] 프로그래머스 N-Queen -연습문제- -백트랙킹- (0) | 2020.05.16 |
Comments