C# 15651번 N과 M(3)
2022. 1. 17. 16:45ㆍ코딩테스트 문제 풀이/[백준] 백트래킹
728x90
반응형
using System;
using System.Text;
namespace beakjoon
{
class _3
{
static int range, length, count;
// 값 출력을 위한 정수 배열
static int[] arr = new int[9];
// 중복 제거를 위한 bool 배열
static bool[] visited = new bool[9];
// 중복 제거를 위한 bool 배열
static StringBuilder output = new StringBuilder();
//DFS 알고리즘
public static void DFS(int cnt, int max)
{
if (count == max)
Console.WriteLine(output);
if (cnt == length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append($"{arr[i]} ");
}
output.AppendLine(sb.ToString());
count += 1;
//Console.WriteLine(sb);
if (count == max)
Console.WriteLine(output);
}
// 문자열 완성이 안됬을 시 반복
else
{
for (int i = 1; i <= range; i++)
{
arr[cnt] = i;
// 재귀 호출
DFS(cnt + 1, max);
}
}
}
public static void Main(string[] args)
{
string temp = Console.ReadLine();
StringBuilder output = new StringBuilder();
string[] read = temp.Split(' ');
//수열의 범위
range = Int32.Parse(read[0]);
//문자열의 길이
length = Int32.Parse(read[1]);
int max = range;
for (int i = 0; i < length - 1; i++)
{
max *= range;
}
DFS(0, max);
}
}
}
코드 설명 :
기본적인 코드는 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
원래는 visited[]를 추가하여 이 숫자가 이미 사용되었는가 아닌가를 확인하는 코드가 있으나 그걸 제외하면 된다.
깃허브 :
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# 15652번 N과 M(4) (0) | 2022.01.17 |
C# 15650번 N과 M(2) (0) | 2022.01.17 |
C# 15649번 N과 M(1) (0) | 2022.01.17 |