Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
6
Indexable
#include<iostream>

using namespace std;

char sudoku[9][9];

bool kiemTraTheoHangVaCot() {
	bool ketQua = true;
	for (int i = 0; i < 9; i++)
	{
		bool visitTheoHang[10] = {false};
		bool visitTheoCot[10] = {false};
		for (int k = 0; k < 9; k++)
		{
			// kiem tra theo hang
			if (sudoku[i][k] != '.') {
				// neu khong phai dau .
				// thi kiem tra xem so nay da tung gap chua
				int num = sudoku[i][k] - '0'; // chuyen so kieu char ve kieu int
				if (visitTheoHang[num]) {
					ketQua = false;
					i = 9;
					break;
				}
				visitTheoHang[num] = true;
			}

			// kiem tra theo cot
			if (sudoku[k][i] != '.') {
				// neu khong phai dau .
				// thi kiem tra xem so nay da tung gap chua
				int num = sudoku[k][i] - '0'; // chuyen so kieu char ve kieu int
				if (visitTheoCot[num]) {
					ketQua = false;
					i = 9;
					break;
				}
				visitTheoCot[num] = true;
			}
		}
	}
	return ketQua;
}


bool kiemTraMaTranCon(int startR, int startC) {
	bool visit[10] = {false};
	for (int r = startR; r < startR + 3; r++)
	{
		for (int c = startC; c < startC + 3; c++)
		{
			if (sudoku[r][c] == '.') {
				continue;
			}

			int num = sudoku[r][c] - '0';
			if (visit[num]) {
				return false;
			}
			visit[num] = true;
		}
	}
	return true;
}

int main() {
	//freopen("Text.txt", "r", stdin);

	int T;
	cin >> T;

	for (int testCase = 1; testCase <= T; testCase++)
	{
		cout << "#" << testCase << " ";
		// input
		for (int i = 0; i < 9; i++)
		{
			cin >> sudoku[i];
		}

		// kiem tra theo hang va cot
		if (!kiemTraTheoHangVaCot()) {
			// neu ket qua la false thi in ra 0
			cout << 0 << endl;
			continue; // sang test case tiep theo
		}

		// tiep tuc kiem tra ma tran con 3x3
		// bat dau kiem tra tu goc tren cung ben trai cua moi ma tran con 3x3
		bool ketQua = true;
		for (int i = 0; i < 9; i += 3)
		{
			for (int k = 0; k < 9; k += 3)
			{
				if (!kiemTraMaTranCon(i, k)) {
					ketQua = false;
					i = 9;
					break;
				}
			}
		}

		if (ketQua) {
			cout << 1 << endl;
		} else {
			cout << 0 << endl;
		}
	}

	return 0;
}