반응형
풀이 )
빈칸에 해당되는 칸을 blank 벡터에 집어 넣는다.
이후 빈칸을 한 칸씩 1부터 9까지 가능한 숫자를 check( )를 통해 확인하여 집어 넣는다.
(9까지 모두 불가능하다면, 해당 경우는 종료)
가능한 경우가 나오면 바로 출력하고 프로그램을 종료하기 위해 blank가 비었을 때 바로 출력하고 exit(0)을 호출한다.
#include <iostream>
#include <vector>
using namespace std;
int board[9][9];
bool check(int x, int y, int num){
for(int r = 0; r < 9; ++r){
if(board[r][y] == num)
return false;
}
for(int c = 0; c < 9; ++c){
if(board[x][c] == num)
return false;
}
for(int r = x/3*3; r < x/3*3+3; ++r){
for(int c = y/3*3; c < y/3*3+3; ++c){
if(board[r][c] == num)
return false;
}
}
return true;
}
void dfs(vector<int>& blank){
if(blank.empty()){
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
cout << board[i][j];
if(j == 8)
cout << '\n';
else
cout << ' ';
}
}
exit(0);
}
int x = blank.back()/10;
int y = blank.back()%10;
blank.pop_back();
for(int i = 1; i < 10; ++i){
if(!check(x, y, i))
continue;
board[x][y] = i;
dfs(blank);
board[x][y] = 0;
}
blank.push_back(x*10+y);
}
int main(void){
vector<int> blank;
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
cin >> board[i][j];
if(board[i][j] == 0)
blank.push_back(i*10+j);
}
}
dfs(blank);
}
반응형
'문제풀이 > 백준' 카테고리의 다른 글
[C++] 백준 - 1744 : 수 묶기 (0) | 2021.01.15 |
---|---|
[C++] 백준 - 1068 : 트리 (0) | 2021.01.13 |
[C++] 백준 - 10942 : 팰린드롬? (0) | 2021.01.13 |
[C++] 백준 - 11559 : Puyo Puyo (0) | 2021.01.11 |
[C++] 백준 - 15686 : 치킨 배달 (0) | 2021.01.06 |