알고리즘/BAEKJOON
백준 2580번 스도쿠
pureworld
2019. 6. 30. 17:01
백준 2580번 스도쿠
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <iostream> #include <cstdio> #include <stack> #include<algorithm> using namespace std; int arr[10][10]; bool CheckRow(int y, int target) { for (int i = 0; i < 9; i++) { if (arr[y][i] == target) return false; } return true; } bool CheckCol(int x, int target) { for (int j = 0; j < 9; j++) { if (arr[j][x] == target) return false; } return true; } bool CheckBox(int y, int x, int target) { int a = y / 3; int b = x / 3; a *= 3; b *= 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (arr[a + i][b + j] == target) return false; } } return true; } bool isTrue(int y, int x, int target) { if (CheckRow(y, target) && CheckCol(x, target) && CheckBox(y, x, target)) return true; return false; } bool sdoku() { int y, x; bool Check = true; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (arr[i][j] == 0) { Check = false; y = i; x = j; break; } } if (!Check) break; } if (Check) return true; for (int target = 1; target <= 9; target++) { if (isTrue(y, x, target)) { arr[y][x] = target; if (sdoku()) return true; } arr[y][x] = 0; } return false; } int main() { for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) cin >> arr[i][j]; cout << endl; sdoku(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) cout << arr[i][j] << " "; cout << endl; } return 0; } | cs |
출처:https://www.acmicpc.net/problem/2580
1.가로조건확인.
2.세로조건확인.
3.3*3조건확인.
3가지를 모두 만족시킬수 있는 아무 숫자아 넣으면서 백트래킹을 사용해서 문제를 풀면 AC를 받을 수 있는 문제였습니다.