Einzelnen Beitrag anzeigen
Alt 21.08.06, 01:22   #18 (permalink)
lagalopex
 
Registriert seit: 01.11.03
lagalopex Leistung: Facit NTK
Likes: 0
Standard

Lösung in C++   
Code:
#include <iostream>

/*
Beispiele (eindeutig):
000000000070040010301506408000000000060010040105709803000000000030070020204805709
000105000009060400060000070400010003050402010600030004020000050003090800000206000
000004710080300950000090000307000800006000037050020000000970502400008000090040080
090000002060280070700000030020005000000400009078009600680000005100003040000000300
020900040003014007006005800400560000300000000000102050000006008057000100080000300
*/


using namespace std;

void print_table(short *num)
{
	for(int i = 0 ; i < 81 ; i++) {
		if(num[i])
			cout << num[i];
		else
			cout << " ";
		if(i % 9 == 8) {
			cout << endl;
			if(i % 27 == 26)
				cout << endl;
		}
		else if (i % 3 == 2)
			cout << "  ";
		else
			cout << " ";
	}
}

void crack(short *num, const int pos)
{
	static int number = 0;
	if(pos == 81) {
		cout << ++number << ". solution:" << endl;
		print_table(num);
	}
	else if(num[pos])
		crack(num, pos+1);
	else {
		short a = (pos / 9) * 9, b = pos % 9, c, d, e, i;
		for(i = 1 ; i <= 9 ; i++) {
			for(d = 0 ; d < 9 ; d++) { // horizontal
				if(num[d + a] == i) {
					d = -1;
					break;
				}
			}
			if(d == -1)
				continue;
			for(d = 0 ; d < 9 ; d++) { // vertikal
				if(num[b + d * 9] == i) {
					d = -1;
					break;
				}
			}
			if(d == -1)
				continue;
			c = pos - pos % 3 - (pos / 9 % 3) * 9; // Block
			for(d = 0 ; d < 3 ; d++) {
				for(e = 0 ; e < 3 ; e++) {
					if(num[c + d + e * 9] == i) {
						d = -1;
						break;
					}
				}
				if(d == -1)
					break;
			}
			if(d == -1)
				continue;
			num[pos] = i;
			crack(num, pos + 1);
		}
		num[pos] = 0;
	}
}

int main(int argc, char *argv[])
{
	short num[81];
	int i;
	if(argc != 2 || strlen(argv[1]) != 81) {
		cerr << "usage: " << argv[0] << " [81 digits]" << endl;
		return(1);
	}

	for(i = 0 ; i < 81 ; i++) {
		if(argv[1][i] < '0' || argv[1][i] > '9') {
			cerr << "usage: " << argv[0] << " [81 digits]" << endl;
			return(1);
		}
		num[i] = argv[1][i] - '0';
	}

	print_tables(num);

	crack(num, 0);

	return(0);
}
lagalopex ist offline   Mit Zitat antworten
 

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