[백준]_15651_15656_N과M3,7

`BFS

BFS를 알게 되고 나서 거의 처음 풀어본 문제들. 두 문제의 탐색 방향과 미로 탐색에서 배열을 받아서 푼 것 이외에는 풀이가 거의 비슷하다.


N과 M(3)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class B15651 {

	public static StringBuilder sb = new StringBuilder();
	public static int N, M;
	public static int[] arr;
	public static boolean[] visit;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());

		arr = new int[M];
		visit = new boolean[N+1];
		search(0);
		System.out.println(sb);
	}

	public static void search(int end) {
		if (end == M) {
			for (int i = 0; i < M; i++) {
				sb.append(arr[i]).append(' ');
			}
			sb.append('\n');
			return;
		}
		for (int i = 1; i <= N; i++) {
			if (!visit[i]) {
				visit[i] = true;
				arr[end] = i;
				search(end + 1);
				visit[i] = false;
			}
		}
	}

}

N과 M(7)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class B15656 {
	public static StringBuilder sb = new StringBuilder();
	public static int N, M;
	public static int[] arr, output;
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
 
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
 
		output = new int[N+1];
		st = new StringTokenizer(br.readLine());
        for (int i = 1; i <= N; i++) {
            output[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(output);
		arr = new int[M];
		search(0);
		System.out.println(sb);
	}
	
	public static void search(int depth) {
		if(depth == M) {
			for(int i=0;i<M;i++) {
				sb.append(arr[i]).append(' ');
			}
			sb.append('\n');
			return;
		}
		for(int i=1;i<=N;i++) {
			arr[depth] = output[i];
			search(depth+1);
		}
	}
}
updatedupdated2021-03-012021-03-01
Load Comments?