問題はこちら
http://matome.naver.jp/odai/2134127498258691101
#include <stdio.h>
struct SUUDOKU
{
unsigned int table[9][9];
};
bool check(const struct SUUDOKU suudoku, const unsigned int i, const unsigned int x, const unsigned y)
{
for(unsigned int px = 0; px < 9; px++)
{
if( i == suudoku.table[y][px] )
{
return false;
}
}
for(unsigned int py = 0; py < 9; py++)
{
if( i == suudoku.table[py][x] )
{
return false;
}
}
const unsigned int py_offset = (y/3)*3;
const unsigned int px_offset = (x/3)*3;
for(unsigned int py = py_offset; py < 3+py_offset; py++)
{
for(unsigned int px = px_offset; px < 3+px_offset; px++)
{
if( i == suudoku.table[py][px] )
{
return false;
}
}
}
return true;
}
bool solve(struct SUUDOKU suudoku, const unsigned int x, const unsigned int y)
{
if( y == 9 )
{
for(unsigned int py = 0; py < 9; py++)
{
for(unsigned int px = 0; px < 9; px++)
{
printf("%d ",suudoku.table[py][px]);
}
printf("\n");
}
return true;
}
if( suudoku.table[y][x] != 0 )
{
return solve(suudoku, (x != 8) ? x+1: 0, (x != 8) ? y: y+1);
}
else
{
for(unsigned int i = 1; i <= 9; i++)
{
if( check(suudoku, i, x, y) == false )
{
continue;
}
suudoku.table[y][x] = i;
bool ret = solve(suudoku, (x != 8) ? x+1: 0, (x != 8) ? y: y+1);
if( ret == true )
{
return true;
}
}
return false;
}
}
int main()
{
const struct SUUDOKU suudoku = {{
{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},
{0,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}
}};
solve(suudoku, 0, 0);
getchar();
return 0;
}