백준 풀이 C++

백준 2580 c++ 백트레킹

ag2개발자 2022. 9. 27. 22:47
#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
#define ll long long

int board[9][9];
vector<pair<int, int>> zeros;
int cnt=0;
bool found = false;

bool check(pair<int, int> p) {
	int xs = p.first / 3;
	int ys = p.second / 3;
	for (int i = 0; i < 9; i++) {
		 
			if (board[p.first][i] == board[p.first][p.second]
				&&i!=p.second) {
				return false;
			}
	
			if (board[i][p.second] == board[p.first][p.second]
				&&i!=p.first) {
				return false;
			}
		
	}
	for (int i = 3 * xs; i < 3*xs + 3; i++) {
		for (int j = 3 * ys; j < 3 * ys + 3; j++) {
			if (board[i][j] == board[p.first][p.second]) {
				if (i != p.first && j != p.second)
					return false;
			}
				
		}
	}
	return true;
}

void sudoku(int n) {
	if (cnt == n) {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				cout << board[i][j] << " ";
				
			}
			cout << "\n";
		}
		found = true;
		return;
	}
	for (int j = 1; j <= 9; j++) {
		board[zeros[n].first][zeros[n].second] = j;
		if (check(zeros[n])) {
			sudoku(n + 1);
		}
		if(found)
			return;
	}
	board[zeros[n].first][zeros[n].second] = 0;
	return;
}

int main() {
	cin.tie(0)->sync_with_stdio(0);
	
	pair<int, int> zero;
	for (int i = 0; i < 9; i++) {
		for (int j = 0; j < 9; j++) {
			cin >> board[i][j];
			if (board[i][j] == 0) {
				cnt++;
				zero.first = i;
				zero.second = j;
				zeros.push_back(zero);
			}
		}
	}
	sudoku(0);
	return 0;
}

'백준 풀이 C++' 카테고리의 다른 글

백준 1920 c++ (이분탐색 기초)  (0) 2022.09.27
백준 16401 c++ (이분탐색)  (0) 2022.09.27
백준 1072 C++(이분탐색)  (0) 2022.09.27
백준 1072 c++ 이분탐색  (0) 2022.09.27
백준 2805 C++ (이분탐색)  (0) 2022.09.24