끄적끄적 코딩
article thumbnail
Published 2019. 9. 11. 15:04
[C++] 백준 15649번 N과 M (1) 알고리즘

백트래킹 문제입니다.

DFS를 통해서 수를 하나씩 입력해 나가면서
길이가 m이 되면 출력했습니다.

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

int n, m;
int arr[10];
vector<int> v;

void DFS(int x) 
{
	v.push_back(x);

	if (v.size() == m) {
		for (int i = 0; i < v.size(); ++i) {
			printf("%d ", v[i]);
		}
		printf("\n");
		v.pop_back();
		return;
	}

	for (int i = 1; i <= n; ++i) {
		if (find(v.begin(), v.end(), i) != v.end()) {
			continue;
		}
		DFS(i);
	}
	v.pop_back();
}

int main(int argc, char* argv[])
{
	scanf("%d", &n);
    scanf("%d", &m);

	for (int i = 1; i <= n; ++i) {
		arr[i] = i;
	}

	for (int i = 1; i <= n; ++i) {
		DFS(i);
	}

	return 0;
}

'알고리즘' 카테고리의 다른 글

[C++] 백준 15651번 N과 M (3)  (0) 2019.09.11
[C++] 백준 15650번 N과 M (2)  (0) 2019.09.11
[C++] 백준 2206번 벽 부수고 이동하기  (0) 2019.09.11
[C++] 백준 7569번 토마토  (0) 2019.09.11
[C++] 백준 7576번 토마토  (0) 2019.09.11

검색 태그