Posts

Showing posts with the label Backtracking

Rat in Maze

/*** Rat in a Maze A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves. IDEA: Similar with Robot walking. Start from maze[N-1][N-1], find the path back to maze[0][0]. check the validation before move. maze[m][n], two direction,maze[m-1][n] and maze[m][n-1]. ***/ #include <iostream> #include <vector> using namespace std; #define N 4 //width of Maze struct point {   ...

Sudoku

/*** Sudoku Given a partially filled 9×9 2D array ‘grid[9][9]‘, the goal is to assign digits (from 1 to 9) to the empty cells so that every row,   column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9. Backtracking Algorithm Like all other Backtracking problems, we can solve Sudoku by one by one assigning numbers to empty cells.  Before assigning a number, we check whether it is safe to assign. We basically check that the same number  is not present in current row, current column and current 3X3 subgrid. After checking for safety,  we assign the number, and recursively check whether this assignment leads to a solution or not.  If the assignment doesn’t lead to a solution, then we try next number for current empty cell.  And if none of number (1 to 9) lead to solution, we return false. ***/ #include <iostream> using namespace std; class Sudoku { public :      ...