www.acmicpc.net/problem/2644

 

2644번: 촌수계산

사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진

www.acmicpc.net

BFS 코드

촌수를 찾는다는건 가장 짧은 거리를 찾는 것과 같다고 볼 수있으므로 BFS를 이용할 수있다.

if (map[abc][i] == 1 && arr[i] == 0)

arr배열을 통해 거리값들을 받으면서 지나오지않은 노드만 queue에 넣어준다.

#include<iostream>
#include <queue>
using namespace std;
int N, X, Y, M;
int map[101][101];
int arr[101];
void bfs(int start, int end) {
	queue<int> q;
	q.push(start);
	arr[start] = 1;
	
	while (!q.empty()) {
		int abc = q.front();
		q.pop();
		for (int i = 1; i <= N; i++) {//다음노드탐색
			if (map[abc][i] == 1 && arr[i] == 0) { //부모가 될수 있는가 + 이미 다녀온 노드 아닌경우 
				q.push(i);
				arr[i] = arr[abc] + 1;
			}
		}

	}
}
int main() {
	cin >> N >> X >> Y >> M;

	for (int i = 0; i < M; i++) {
		int a, b;
		cin >> a >> b;
		map[a][b] = 1;
		map[b][a] = 1;

	}
	bfs(X, Y);

	if (arr[Y] != 0) {
		cout << arr[Y];
	}
	else cout << -1;




	return 0;
}

 

 

 

DFS 코드

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int N, X, Y, M;
int map[101][101];
int visited[101];
bool flag;
int cnt;
void dfs(int p, int s,int level,int before) { //이전값 들고다니기 
	if (p == s) {
		flag = true;
		cnt = level;
		return;
	}

	for (int i = 1; i <= N; i++) {
		if (map[p][i] == 1) {
			if (i == before) continue; 	//양방향 트리이므로 cycle을 방지하기위해 before

			dfs(i, s, level + 1,p);
		}

	}

}

int main() {
	cin >> N >> X >> Y >> M;

	for (int i = 0; i < M; i++) {
		int a, b;
		cin >> a >> b;
		map[a][b] = 1;
		map[b][a] = 1;

	}


	dfs(X,Y,0,0);
	if (cnt == 0) cout << -1;
	else cout << cnt;


	return 0;
}

'알고리즘 공부 > 백준' 카테고리의 다른 글

[백준] 나이트의 이동(C++/7562번)  (0) 2021.05.06
[백준] 1로만들기 (C++/1463번)  (0) 2021.05.05
[백준] 단지번호붙이기  (0) 2021.05.02
[백준] 문자열  (0) 2021.05.02
[백준] 섬의 개수  (0) 2021.04.28

https://programmers.co.kr/learn/courses/30/lessons/43165

 

코딩테스트 연습 - 타겟 넘버

n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+

programmers.co.kr

코드 설명

연산 (-,+)을 branch로 생각하여 DFS를 구성하였다.

처음 main문에서 넘겨주는 값을 number[level]로 했다가 바닥조건에서 이를 고려안해서 실수했다....

프로그래머스 환경에서 dfs 디버깅은 좀 쉽지 않은것 같다...

 

코드

#include <string>
#include <vector>

using namespace std;
int arr[2]={-1,1};
int answer=0;
void dfs(int level,int now,vector<int>&numbers,int target){
    if(level==numbers.size()){
        if(now==target) answer++;
        return;
    }
    for(int i=0;i<2;i++){
        int sum=numbers[level]*arr[i];
        now+=sum;
    
        dfs(level+1,now,numbers, target);
        now-=sum;
        
    }
    
}
int solution(vector<int> numbers, int target) {
    
    
    int n=numbers.size();
    dfs(0,0,numbers,target);
    
    return answer;
}

'알고리즘 공부 > 프로그래머스' 카테고리의 다른 글

[프로그래머스] 더 맵게  (0) 2021.05.01
[프로그래머스] 프린터  (0) 2021.04.30
[프로그래머스] 기능개발  (0) 2021.04.30
[프로그래머스] 입국심사  (0) 2021.04.27
[프로그래머스] H-Index  (0) 2021.04.27

+ Recent posts