[수학] (조합론) backtracking으로 2차원 배열의 조합 탐색하기자료구조 | 알고리즘/수학2023. 11. 28. 23:58
      Table of Contents
        728x90
    
    
  반응형
    
    
    
  [백준] 14502번 연구소를 풀다가 화딱지가 나서 겨우겨우 구현했다. 이게 과연 쓸 일이 있을까 해서 그냥 남겨둔다. 백트래킹으로 1차원 배열의 조합은 구현해봤어도 2차원 배열의 조합은 처음 해본다. 생각보다 생각해내기 어려웠다.... 직접 손으로 써보면서 겨우 찾아냈다..
y좌표가 증가하는 순으로 x좌표가 무조건 0부터n-1까지가 아니라
다음 탐색에서 y랑 같을 때만 x이고 그 다음부터는 0부터 n-1까지이다.
x부터가 아니라 바로 x+1부터로 하면 되지 않냐? 하는 의문이 들지만 해보면 처음 채울 때에 첫째칸이 안채워진다. 따라서 x부터 하는게 맞다.
#include<iostream>
using namespace std;
int map[4][4];
int cnt;
void print() {
	for (int i = 0; i < 4; i++) {
		for (int j = 0; j < 4; j++) cout << map[i][j] << " ";
		cout << "\n";
	}
}
void backtracking(int cur,int y, int x) {
	if (cur == 3) {
		cout << ++cnt << "회: \n";
		print();
		return;
	}
	for (int i = y; i < 4; ++i) {
		//입력받은 y에 대하여 처음에만(i == y인 경우) x부터 시작, 나머지는 0부터 시작
		int j =  i == y ? x : 0;
		for (; j < 4; j++) {
			if (!map[i][j]) {
				map[i][j] = 1;
				backtracking(cur + 1, i, j);
				map[i][j] = 0;
			}
		}
	}
}
int main(void) {
	backtracking(0, 0, 0);
}
728x90
    
    
  반응형
    
    
    
  '자료구조 | 알고리즘 > 수학' 카테고리의 다른 글
| PS를 위한 정수론 (0) | 2024.04.09 | 
|---|---|
| [알고리즘] 자릿수 구하기 (0) | 2023.12.15 | 
| [알고리즘] 자릿수 분해하기 (0) | 2023.12.15 | 
| 퓨리에 변환을 이용한 FFT를 이용한 곱셈 계산 예제문제 (0) | 2023.12.05 | 
| [수학] 조건, 반복문으로 순열, 중복순열, 중복조합 출력하기 (0) | 2023.11.16 | 
@BE_개발자 :: 경이로운 개발일기
            경이로운 BE 개발자가 되기 위한 프로그래밍 공부 기록장
도움이 되었다면 "❤️" 또는 "👍🏻" 해주세요! 문의는 아래 이메일로 보내주세요.
![[알고리즘] 자릿수 구하기](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FtPCk6%2FbtsBY7icGmy%2FAAAAAAAAAAAAAAAAAAAAAHHuiesB8eXoJbz-r36g7YnrZzh6_73vd5Jdlval6lZw%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1764514799%26allow_ip%3D%26allow_referer%3D%26signature%3D9jvpJ3Yw%252FuMOZWalCz59GfHAMQo%253D) 
                  ![[알고리즘] 자릿수 분해하기](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2Fbolvgq%2FbtsB5BIFGhK%2FAAAAAAAAAAAAAAAAAAAAABm4CLJ5XZfdI07KdmN8roVvAGZPLL06-5lf557gj61E%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1764514799%26allow_ip%3D%26allow_referer%3D%26signature%3Daq4jDac%252FxyCZvtAuc05WgoTTjKI%253D) 
                   
                  ![[수학] 조건, 반복문으로 순열, 중복순열, 중복조합 출력하기](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FBwuHu%2FbtsAm0LXyd4%2FAAAAAAAAAAAAAAAAAAAAAPyx3iOqrVGxkVbu_pFpDV7dSaAnCuBE1vEsAp7DXBe4%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1764514799%26allow_ip%3D%26allow_referer%3D%26signature%3DEHJ1GYXHCGNqTtPmEVt7%252Bn7HO9Y%253D)