backtracking

N-Queens Puzzle

December 23, 2023
medium
backtracking, Constraint Satisfaction

Problem # Place N queens on an N x N chessboard such that no two queens can attack each other. Solution # The Python code for solving the “N Queens” problem is provided below. This problem involves placing N queens on an N x N chessboard such that no two queens can attack each other. A solution to the problem means that no two queens share the same row, column, or diagonal. ...

K-Sum

December 20, 2023
medium
backtracking

Problem # Given an integer k and a list of integers, find if there exists k numbers in the list that add up to 0. Return true if such a set is possible, false otherwise. Solution # def can_find_k_sum(nums, k, start, target): # If k is 0, then we have found a combination that sums up to the target if k == 0: return target == 0 # If we have run out of numbers to add, return False if start == len(nums): return False # Include the current number and check if a combination is possible if can_find_k_sum(nums, k - 1, start + 1, target - nums[start]): return True # Exclude the current number and check if a combination is possible return can_find_k_sum(nums, k, start + 1, target) def can_partition_k(nums, k): # Edge case: if we don't have enough numbers if len(nums) < k: return False return can_find_k_sum(nums, k, 0, 0) # Test the function with an example print(can_partition_k([-5, -3, -2, -1, 0, 1, 2, 3, 4, 5], 3)) # Should return True as there are combinations that sum up to 0 can_find_k_sum is a helper function that uses recursion and backtracking to find if there exists a combination of k numbers that sum up to the target (in this case, 0). ...

Word Search

December 18, 2023
medium
DFS, graph, backtracking

Problem # Given a 2D board of letters and a target word, find all occurrences of the word in the board. Solution # Below is the complete Python code for the function find_word_occurrences, which finds all occurrences of a given word in a 2D board of letters. You can use this code in your Python environment: def find_word_occurrences(board, word): if not board or not word: return [] def dfs(board, word, index, x, y): if index == len(word): return True if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]) or board[x][y] ! ...