C# 15652번 N과 M(4)
2022. 1. 17. 16:48ㆍ코딩테스트 문제 풀이/[백준] 백트래킹
728x90
반응형

using System;
using System.Text;
namespace beakjoon
{
class _4
{
static int range, length;
// 값 출력을 위한 정수 배열
static int[] arr = new int[9];
// 배열이 오름차순인지 확인하기 위한 배열
//DFS 알고리즘
public static void DFS(int cnt)
{
// 출력할 배열이 완성되면 문자열 출력
if (cnt == length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append($"{arr[i]} ");
}
Console.WriteLine(sb);
}
// 문자열 완성이 안됬을 시 반복
else
{
for (int i = 1; i <= range; i++)
{
if ((cnt > 0 && arr[cnt - 1] <= i) || cnt == 0)
{
arr[cnt] = i;
}
else
{
continue;
}
// 재귀 호출
DFS(cnt + 1);
}
}
}
public static void Main(string[] args)
{
string temp = Console.ReadLine();
string[] read = temp.Split(' ');
//수열의 범위
range = Int32.Parse(read[0]);
//문자열의 길이
length = Int32.Parse(read[1]);
DFS(0);
}
}
}
코드설명 :
기본적인 틀은 N과 M(1)과 같다. 자세한 코드는 아래 링크에 있다.
C# 15649 N과 M(1)
코드 : using System; using System.Text; namespace beakjoon { class _2 { static int range, length; // 값 출력을 위한 정수 배열 static int[] arr = new int[9]; // 배열이 오름차순인지 확인하기 위한 배..
chlee200530.tistory.com
출력된 값을 보면 오른쪽의 값이 왼쪽보다 크거나 같음을 알 수 있다. 이 조건만 추가해주면 된다.
if ((cnt > 0 && arr[cnt - 1] <= i) || cnt == 0)
{
arr[cnt] = i;
}
else
{
continue;
}
GitHub - CheongHo-Lee/Algorithm-Study: Algorithm Study For Coding Test
Algorithm Study For Coding Test. Contribute to CheongHo-Lee/Algorithm-Study development by creating an account on GitHub.
github.com
728x90
반응형
'코딩테스트 문제 풀이 > [백준] 백트래킹' 카테고리의 다른 글
C# 14888번 연산자 끼워넣기 (0) | 2022.01.17 |
---|---|
C# 9663번 N-Queen (0) | 2022.01.17 |
C# 15651번 N과 M(3) (0) | 2022.01.17 |
C# 15650번 N과 M(2) (0) | 2022.01.17 |
C# 15649번 N과 M(1) (0) | 2022.01.17 |