1. 程式人生 > 其它 >回溯演算法_解數獨1

回溯演算法_解數獨1

Private Function solveSudokuHelper(board) As Boolean
    For i = 0 To 8
        For j = 0 To 8
            If (board(i, j) = ".") Then
                For k = 1 To 9
                    If isValidSudoku(i, j, k, board) Then
                        board(i, j) = k
                        If solveSudokuHelper(board) Then solveSudokuHelper 
= True: Exit Function board(i, j) = "." End If Next solveSudokuHelper = False: Exit Function End If Next Next solveSudokuHelper = True End Function Sub h21_回溯演算法_解數獨1() '陣列起始下標為0 tms = Timer '
程式起始時間 With Sheet1 .Range("m1").CurrentRegion.ClearContents ar = .Range("a1").CurrentRegion Dim board(0 To 8, 0 To 8) For x = 1 To UBound(ar) For y = 1 To UBound(ar, 2) board(x - 1, y - 1) = ar(x, y) Next Next res
= solveSudokuHelper(board) .Range("m1").Resize(UBound(board) + 1, UBound(board, 2) + 1) = board End With MsgBox Format(Timer - tms, "0.0s ") & s End Sub Private Function isValidSudoku(row, col, Val, board) As Boolean For i = 0 To 8 If board(row, i) = Val Then isValidSudoku = False: Exit Function Next For j = 0 To 8 If board(j, col) = Val Then isValidSudoku = False: Exit Function Next startrow = (VBA.Int(row / 3)) * 3 startcol = (VBA.Int(col / 3)) * 3 For i = startrow To startrow + 2 For j = startcol To startcol + 2 If board(i, j) = Val Then isValidSudoku = False: Exit Function Next Next isValidSudoku = True End Function