01-24 04:40
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_57 ์ค‘๋ณต ์ˆœ์—ด ๊ตฌํ•˜๊ธฐ(DFS) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_57 ์ค‘๋ณต ์ˆœ์—ด ๊ตฌํ•˜๊ธฐ(DFS)

miinsun 2022. 3. 2. 18:39

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

1๋ถ€ํ„ฐ N๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ ํžŒ ๊ตฌ์Šฌ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ค‘ ์ค‘๋ณต์œผ ํ—ˆ๋ฝํ•˜์—ฌ M๋ฒˆ์„ ๋ฝ‘์•„ ์ผ๋ ฌ๋กœ ๋‚˜์—ดํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ชจ๋‘ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=10)๊ณผ M(2<=M<=N)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

3 2

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. ์ถœ๋ ฅ ์ˆœ์„œ๋Š” ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. 

1 1 
1 2 
1 3 
2 1 
2 2 
2 3 
3 1 
3 2 
3 3

 

โœจ ์•„์ด๋””์–ด

โ€‹

m๋ฒˆ์˜ ๋ฝ‘๊ธฐ๋กœ ๋ฝ‘์„ ์ˆ˜ ์žˆ๋Š” ํ•œ๋ฒˆ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ PM์— ์ €์žฅํ•˜์ž (pm[m]).

๊ธฐ์กด์˜ ์œ ๋ฌด๋ฅผ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฌธ์ œ๋“ค๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ(์ด์ง„ ํŠธ๋ฆฌ), 1~N๊นŒ์ง€์˜ ๊ฐ€๋Šฅ์„ฑ์„ ๋ชจ๋‘ ์กฐ์‚ฌํ•œ๋‹ค.

 

  • ์žฌ๊ท€ ํƒˆ์ถœ ์กฐ๊ฑด
    • ์ตœ๋Œ€ ๋ ˆ๋ฒจ์— ๋„๋‹ฌํ•˜๋ฉด return

 

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	static int[] pm;
	static int n, m;
	public void DFS(int L) {
		if(L == m) {
			for(int i = 0; i < m; i++) {
				System.out.print(pm[i] + " ");
			}
			System.out.println();
		}
		else {
			for(int i = 1; i <= n; i++) {
				pm[L] = i;
				DFS(L + 1);
			}
		}
 	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt(); // ๋ฒˆํ˜ธ
		m = sc.nextInt(); // ๋ฝ‘์„ ๊ฐฏ์ˆ˜
		
		pm = new int[m];
		main.DFS(0);
		
		sc.close();
		return ;
	}
}
Comments