九宫格计算的代码,可扩展到任意尺寸。
// nine.cpp : 定义控制台应用程序的入口点。 // #include <stdio.h> #include <tchar.h> #include <stdlib.h> const int w = 9; int s[] = { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 0, 0, 0, 0, 0, 7, 0, 0, 9, 0, 2, 0, 0, 0, 5, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 4, 5, 7, 0, 0, 2, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 6, 8, 0, 0, 8, 5, 0, 0, 0, 1, 0, 0, 9, 0, 0, 0, 0, 4, 0, 0, }; int d[w*w]; bool cal( int m, int n ) { //bool result = false; int m2 = m, n2 = n; if( ++n2 >= w ) { n2 = 0; ++m2; } int k = m*w + n; for( ;; ) { if( !s[k] ) { for( ;; ) { if( ++d[k] > w ) { d[k] = 0; return false; } int i = 0; for( ; (i < w && d[ m*w + i] != d[k]) || i == n; i++ ); if( i != w ) continue; for( i = 0; (i < w && d[ i*w + n ] != d[k]) || i == m; i++ ); if( i != w ) continue; break; } } if( m == w-1 && n == w-1 ) return true; if( cal( m2, n2 ) ) return true; if( s[k] ) return false; } return false; } int _tmain(int argc, _TCHAR* argv[]) { if( sizeof(s) / sizeof(*s) != w * w ){ printf( "数据错误。" ); system("pause"); return -1; } memcpy( d, s, sizeof(s) ); if( !cal(0, 0) ) { printf( "无解。" ); system("pause"); return -2; } for( int i = 0; i < w; i++ ) { for( int j = 0; j < w; j++ ) { printf( "%i,", d[i*w+j] ); } printf( "\r\n" ); } system("pause"); return 0; }
原文:http://blog.csdn.net/hhhh63/article/details/23690605