数独输出Java_java – 使用回溯的数独求解器

我最近一直致力于回溯数独求解算法,目前我想询问我应该如何将我的solve()方法从void更改为boolean.

我正在使用一个非常简单的回溯算法,它目前工作正常,但我宁愿有一个布尔值而不是一个空格,因为有一个printstack不是很好…

谢谢!

public class Backtracking{

static int backtrack = 0;

//check if valid in row

protected static boolean validInRow(int row,int value)

{

for( int col = 0; col < 9; col++ )

if( board[row][col] == value )

return false ;

return true ;

}

//check if valid in column

protected static boolean validInCol(int col,int value)

{

for( int row = 0; row < 9; row++ )

if( board[row][col] == value )

return false ;

return true ;

}

//check if valid in 3*3

protected static boolean validInBlock(int row,int col,int value)

{

row = (row / 3) * 3 ;

col = (col / 3) * 3 ;

for( int r = 0; r < 3; r++ )

for( int c = 0; c < 3; c++ )

if( board[row+r][col+c] == value )

return false ;

return true ;

}

//call other methods

public void solve(int row,int col) throws Exception

{

if(row > 8)

throw new Exception("Solution found") ;

else

{

while(board[row][col] != 0)

{

if( ++col > 8 )

{

col = 0 ;

row++ ;

if( row > 8 )

throw new Exception( "Solution found" ) ;

}

}

for(int value = 1; value < 10; value++)

{

if(validInRow(row,value) && validInCol(col,value) && validInBlock(row,col,value))

{

board[row][col] = value;

new PrintEvent(board);

if( col < 8 )

solve(row,col + 1);

else

solve(row + 1,0);

backtrack++;

}

}

board[row][col] = 0;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值