Close Menu
    Trending
    • Prescriptive Modeling Makes Causal Bets – Whether you know it or not!
    • A Gentle Introduction to Backtracking
    • Lessons Learned After 6.5 Years Of Machine Learning
    • From Pixels to Plots | Towards Data Science
    • Become a Better Data Scientist with These Prompt Engineering Tips and Tricks
    • Accelerating scientific discovery with AI | MIT News
    • Baidu släpper ERNIE 4.5 som öppen källkod
    • En ny rapport avslöjar våra AI-favoriter
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » A Gentle Introduction to Backtracking
    Artificial Intelligence

    A Gentle Introduction to Backtracking

    ProfitlyAIBy ProfitlyAIJune 30, 2025No Comments9 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    is a flexible method for exploring the answer house of assorted forms of knowledge science issues and incrementally developing candidate options – a bit like navigating a maze. On this article, we are going to briefly go over the idea of backtracking earlier than diving into a few intuitive, hands-on examples coded in Python.

    Be aware: All instance code snippets within the following sections have been created by the creator of this text.

    Conceptual Overview

    At a excessive degree, the backtracking method includes a step-by-step exploration of the answer house of a computational drawback (often an issue that may be framed as one in all constraint satisfaction or combinatorial optimization). At every step within the exploration, we proceed alongside completely different paths, checking that the issue constraints are glad as we go alongside.

    If we come across a legitimate answer throughout our exploration, we make an observation of it. At this level, we will finish the search if our drawback solely requires us to seek out one legitimate answer. If the issue calls for locating a number of (or all) attainable options, we will proceed to discover extensions of the beforehand found answer.

    Nevertheless, if at any level the issue constraints are violated, we backtrack; this implies going again to the final level in our search the place a partial answer had been constructed (and the place legitimate options nonetheless appeared attainable), and persevering with our search alongside a distinct path from there. This forward-and-backward technique of exploration will be continued as wanted till the whole answer house is explored and all legitimate options are explored.

    Fingers-On Examples

    Fixing a Sudoku

    A Sudoku puzzle is a basic instance of a constraint satisfaction drawback with sensible functions in various fields starting from operations research to cryptography. The usual model of the puzzle consists of a 9-by-9 grid, fabricated from 9 non-overlapping 3-by-3 sub-grids (or blocks). Within the beginning configuration of the puzzle, a few of the 81 cells within the grid are prefilled with digits starting from 1 to 9. To finish the puzzle, the remaining cells should be stuffed with digits from 1 to 9 whereas adhering to the next constraints: no row, column, or 3-by-3 block could include a replica digit.

    The Python code under reveals find out how to implement a Sudoku solver utilizing backtracking, together with a comfort operate for pretty-printing the grid. Be aware that the solver expects empty cells to be denoted (or initialized) with zeros.

    from copy import deepcopy
    
    def is_valid(board, row, col, num):
        # Test if num shouldn't be within the present row or column
        for i in vary(9):
            if board[row][i] == num or board[i][col] == num:
                return False
        # Test if num shouldn't be within the 3-by-3 block
        start_row, start_col = 3 * (row // 3), 3 * (col // 3)
        for i in vary(start_row, start_row + 3):
            for j in vary(start_col, start_col + 3):
                if board[i][j] == num:
                    return False
        return True
    
    def find_empty_cell(board):
        # Discover the subsequent empty cell (denoted by 0)
        # Return (row, col) or None if puzzle is full
        for row in vary(9):
            for col in vary(9):
                if board[row][col] == 0:
                    return row, col
        return None
    
    def solve_board(board):
        empty = find_empty_cell(board)
        if not empty:
            return True  # Solved
        row, col = empty
        for num in vary(1, 10):
            if is_valid(board, row, col, num):
                board[row][col] = num
                if solve_board(board):
                    return True
                board[row][col] = 0  # Backtrack
        return False
    
    def solve_sudoku(start_state):
        board_copy = deepcopy(start_state)  # Keep away from overwriting authentic puzzle
        if solve_board(board_copy):
            return board_copy
        else:
            increase ValueError("No answer exists for the given Sudoku puzzle")
    
    def print_board(board):
        for i, row in enumerate(board):
            if i > 0 and that i % 3 == 0:
                print("-" * 21)
            for j, num in enumerate(row):
                if j > 0 and j % 3 == 0:
                    print("|", finish=" ")
                print(num if num != 0 else ".", finish=" ")
            print()

    Now, suppose we enter a Sudoku puzzle, initializing empty cells with zeros, and run the solver as follows:

    puzzle = [
        [5, 0, 0, 0, 3, 0, 0, 0, 7],
        [0, 0, 0, 4, 2, 7, 0, 0, 0],
        [0, 2, 0, 0, 6, 0, 0, 4, 0],
        [0, 1, 0, 0, 9, 0, 0, 2, 0],
        [0, 7, 0, 0, 0, 0, 0, 5, 0],
        [4, 0, 6, 0, 0, 0, 7, 0, 1],
        [0, 4, 2, 0, 7, 0, 6, 1, 0],
        [0, 0, 0, 0, 4, 0, 0, 0, 0],
        [7, 0, 0, 9, 5, 6, 0, 0, 2],
    ]
    
    answer = solve_sudoku(puzzle)
    print_board(answer)

    The solver will produce the next answer inside milliseconds:

    5 6 4 | 1 3 9 | 2 8 7 
    1 9 8 | 4 2 7 | 5 6 3 
    3 2 7 | 8 6 5 | 1 4 9 
    ---------------------
    8 1 5 | 7 9 4 | 3 2 6 
    2 7 9 | 6 1 3 | 8 5 4 
    4 3 6 | 5 8 2 | 7 9 1 
    ---------------------
    9 4 2 | 3 7 8 | 6 1 5 
    6 5 3 | 2 4 1 | 9 7 8 
    7 8 1 | 9 5 6 | 4 3 2

    Cracking a Math Olympiad Downside

    Math Olympiads are competitions for pre-university college students and include powerful math issues that should be solved underneath timed circumstances with out using calculators. Since systematically exploring the complete answer house for such issues is usually not possible, profitable answer approaches are likely to depend on analytical reasoning and mathematical ingenuity, exploiting express and implicit constraints gleaned from the issue assertion to streamline the search of the answer house. Some issues should do with constraint satisfaction and combinatorial optimization, which we additionally come throughout in knowledge science issues in trade (e.g., checking whether or not a path to a given vacation spot exists, discovering all attainable paths to a vacation spot, discovering the shortest path to a vacation spot). Thus, even when a intelligent mathematical answer strategy exists for a particular Olympiad drawback, it may be instructive to research different generalizable approaches (like backtracking) that exploit the facility of at this time’s computer systems and can be utilized to unravel a broad vary of comparable issues in apply.

    For instance, contemplate the following problem that appeared in Spherical 1 of the British Mathematical Olympiad in November 2018: “An inventory of 5 two-digit optimistic integers is written in growing order on a blackboard. Every of the 5 integers is a a number of of three, and every digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 seems precisely as soon as on the blackboard. In what number of methods can this be accomplished? Be aware {that a} two-digit quantity can’t start with the digit 0.”

    Because it occurs, the answer to the above drawback is 288. The video under explains an answer strategy that cleverly exploits some key express and implicit options of the precise drawback assertion (e.g., the answer should be offered as an ordered checklist, and a quantity is a a number of of three if the sum of its digits can also be a a number of of three).

    The Python code under reveals how backtracking can be utilized to unravel the issue:

    def is_valid_combination(numbers):
        # Checks if every digit from 0-9 seems precisely as soon as in an inventory of numbers
        digits = set()
        for quantity in numbers:
            digits.replace(str(quantity))
        return len(digits) == 10
    
    def find_combinations():
        multiples_of_3 = [i for i in range(12, 100) 
                            if i % 3 == 0 and '0' not in str(i)[0]]
        valid_combinations = []
        def backtrack(begin, path):
            if len(path) == 5:
                if is_valid_combination(path):
                    valid_combinations.append(tuple(path))
                return
            for i in vary(begin, len(multiples_of_3)):
                backtrack(i + 1, path + [multiples_of_3[i]])
        backtrack(0, [])
        return valid_combinations
        
    print(f"Answer: {len(find_combinations())} methods")

    The operate is_valid_combination() specifies the important thing constraint that should maintain for every legitimate 5-number checklist found throughout the exploration of the search house. The checklist multiples_of_3 options the candidate numbers that will seem in a legitimate 5-number checklist. The operate find_combinations() applies backtracking to effectively check out all distinctive 5-number combos from multiples_of_3.

    The operate is_valid_combination() and the checklist comprehension used to generate multiples_of_3 will be modified to unravel a broad vary of comparable issues.

    Past Backtracking

    As we have now seen, backtracking is an easy but highly effective method for fixing several types of constraint satisfaction and combinatorial optimization issues. But, different strategies reminiscent of depth-first search (DFS) and dynamic programming (DP) additionally exist and will look comparable on the floor – so when does it make sense to make use of backtracking as a substitute of those different strategies?

    Backtracking will be considered a extra strategic type of DFS, wherein constraint checking is a core function of every resolution step, and invalid paths will be deserted early. In the meantime, DP could also be used for issues that exhibit two properties: overlapping subproblems and an optimum substructure. An issue has overlapping subproblems if the identical subproblems should be solved a number of instances whereas fixing the bigger drawback; storing and reusing the outcomes of the recurring subproblems (e.g., utilizing memoization) is a key function of DP. Moreover, an issue has an optimum substructure if an optimum answer to the issue will be constructed by constructing on optimum options to its subproblems.

    Now, contemplate the N-Queens Downside, which seems at find out how to place N queens on an N-by-N chessboard, such that no two queens can assault one another; it is a basic drawback that has functions in a number of real-world situations the place discovering options with out conflicts is essential (e.g., useful resource allocation, scheduling, circuit design, and path planning for robots). The N-Queens drawback doesn’t inherently exhibit overlapping subproblems or an optimum substructure, since subproblems could not essentially should be solved repeatedly to unravel the general drawback, and the location of queens in a single a part of the board doesn’t assure an optimum placement for the whole board. The inherent complexity of the N-Queens Downside thus makes it much less appropriate for exploiting the strengths of DP, whereas backtracking aligns extra naturally with the issue’s construction.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleLessons Learned After 6.5 Years Of Machine Learning
    Next Article Prescriptive Modeling Makes Causal Bets – Whether you know it or not!
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    Prescriptive Modeling Makes Causal Bets – Whether you know it or not!

    June 30, 2025
    Artificial Intelligence

    Lessons Learned After 6.5 Years Of Machine Learning

    June 30, 2025
    Artificial Intelligence

    From Pixels to Plots | Towards Data Science

    June 30, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Features, Benefits, Reviews and Alternatives • AI Parabellum

    June 27, 2025

    Who Let The Digital Genies Out?

    April 9, 2025

    Retrieval Augmented Classification: Improving Text Classification with External Knowledge

    May 7, 2025

    Helping machines understand visual content with AI | MIT News

    June 9, 2025

    Unlocking the hidden power of boiling — for energy, space, and beyond | MIT News

    April 7, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    A Basic to Advanced Guide for 2025

    April 4, 2025

    AI learns how vision and sound are connected, without human intervention | MIT News

    May 22, 2025

    A Data Scientist’s Guide to Docker Containers

    April 8, 2025
    Our Picks

    Prescriptive Modeling Makes Causal Bets – Whether you know it or not!

    June 30, 2025

    A Gentle Introduction to Backtracking

    June 30, 2025

    Lessons Learned After 6.5 Years Of Machine Learning

    June 30, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.