Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

Topic:

Solving N-queen and Josephus Problem using


Backtracking, Stack and Queue respectively
Introduction to Backtracking 2
Backtracking can be defined as a general algorithmic technique that
considers searching every possible combination in order to solve a
computational problem. 
Here, when the algorithm propagates to an end to check if it is a solution or
not, if it is then returns the solution otherwise backtracks to the point one
step behind it to find track to the next point to find solution.

 
Concept of Stack and Queue 3
 Stacks: Stack is collection of elements, that follows the LIFO
order. LIFO stands for Last In First Out, which means element
which is inserted most recently will be removed first. Imagine a
stack of tray on the table. When you put a tray there you put it at
top, and when you remove it, you also remove it from top.
 A stack has a restriction that insertion and deletion of element can
only be done from only one end of stack and we call that position
as top. The element at top position is called top element.
Insertion of element is called PUSH and deletion is called POP.
 Syntax for stack:
1. push( x ) : insert element x at the top of 1. isEmpty ( ) : check whether the stack is
stack. empty or not.
2. pop( ) : removes element from the top of 2. size ( ) : tells the current size of stack .
stack.
3. topElement ( ) : access the top element
of stack.
Concept of Stack and Queue 4
 Queue is a data structure that follows the FIFO principle.
FIFO means First In First Out i.e the element added first
in the queue will be the one to be removed first.
Elements are always added to the back and removed
from the front. Think of it as a line of people waiting for a
bus at the bus stand. The person who will come first will
be the first one to enter the bus.
 Queue supports some fundamental functions:
1. Enqueue: Adds an element to the back of the 1. Size: Returns the size of the queue or the
queue if the queue is not full otherwise it will number of elements in the queue.
print “OverFlow”. 2. IsEmpty: Returns true if the queue is empty
2. Dequeue: Removes the element from the otherwise returns false.
front of the queue if the queue is not empty
otherwise it will print “UnderFlow”.
3. Front: Return the front element of the queue
Difference between Stack and Queue Data Structures 5

Stacks Queues

Stacks are based on the LIFO principle, i.e., the element inserted Queues are based on the FIFO principle, i.e., the element inserted
at the last, is the first element to come out of the list. at the first, is the first element to come out of the list.

Insertion and deletion in stacks takes place only from one end of Insertion and deletion in queues takes place from the opposite
ends of the list. The insertion takes place at the rear of the list
the list called the top. and the deletion takes place from the front of the list.

Insert operation is called push operation. Insert operation is called enqueue operation.

Delete operation is called pop operation. Delete operation is called dequeue operation.

In stacks we maintain only one pointer to access the list, called In queues we maintain two pointers to access the list. The front
pointer always points to the first element inserted in the list and
the top, which always points to the last element present in the
list. is still present, and the rear pointer always points to the last
inserted element.

Stack is used in solving problems works on recursion. Queue is used in solving problems having sequential processing.
N – Queen Problem 6

 The N Queen is the problem of placing N chess queens on an N×N


chessboard so that no two queens attack each other. For example,
following is a solution for 4 Queen problem.

 The expected output is a binary matrix which has 1s for the blocks
where queens are placed. For example, following is the output
matrix for above 4 queen solution.
Josephus Problem 7

 In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem. Following
is the problem statement:
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and
proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is
executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are
removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k
which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial
circle so that you are the last one remaining and so survive.
For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4
is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. 
If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, 1 are killed in order, and person at
position 4 survives.
Solving N-queen Problem 8

 Things to consider
1. While checking safe position for a
queen(we are going in rowise manner),
we have to check upper column, right
upper diagonal, left upper diagonal of
queen
2. If any queen is present in any of this
position, we will return false.
3. We have to consider one queen is placed
in each row or column
Solving N-queen Problem 9
 Backtracking Step
Steps in Solving N-queen Problem 10

 We are creating isSafe


function.
 isSafe will check
whether
the position is correct for
 queen in upper 
column,right upper diago
nal, left upper diagonal
Steps in Solving N-queen Problem 11

 We call recursively and backtrack if
position is not safe for queen
Steps in Solving N-queen Problem 12

 Now in main function, we will allocate


memory to 1d array and printing output
 Output:
Steps in Solving Josephus Problem 13

 In Josephus problem we are using


recurrence relation of it.
Steps in Solving Josephus Problem 14

 Output:
Time and Space Complexity of N-Queen 15

Problem
 Time Complexity
1. The isSafe method takes O(n) time
2. nQueen runs for O(n) time
3. The isSafe condition is present in the loop and also calls nQueen which is
recursive
4. Adding it becomes, T(n) = O(n^2) + n * T(n-1)
5. After solving it, the time complexity of the N-Queen problem is = O(N!)
 Space Complexity
1. Space Complexity of N-Queen problem is O(N)
Time and Space Complexity of Josephus 16

Problem
 Time Complexity of Josephus Problem is O(N)
 Space Complexity of Josephus Problem is O(N)
Applications of Backtracking 17

 Optimization and tactical problems


 Constrains Satisfaction Problem
 Electrical Engineering
 Robotics
 Artificial Intelligence
 Genetic and bioinformatics Algorithm
 Materials Engineering
 Network Communication
 Solving puzzles and path
Problems Solved by Backtracking 18

M-Coloring Problem
N Queen Problem
Rat in Maze Problem
Cryptarithmetic Puzzle
Subset Sum Problem
Sudoku Solving Algorithm
Knight-Tour Problem
Tug-Of-War Problem
Word Break Algorithm
Maximum number by swapping problem
Applications of Stack 19

 The simplest task a stack could be used for is reversing a string. Each letter in a
string is pushed in and then popped off thus reversing the string.
 In backtracking, to get back from current state, we need to store the previous
state. For that purpose, we need stack.
 Another great use of stack is during the function call and return process. After
calling the function, we also have to come back from the function area to the
place, where we have left our control. So we want to resume our task, not restart.
For that reason, we store the address of the program counter into the stack, then
go to the function body to execute it. After completion of the execution, it pops
out the address from stack and assign it into the program counter to resume the
task again.
Applications of Queue 20

 Serving requests on a single shared resource, like a printer, CPU task scheduling
etc.
 In real life scenario, Call Center phone systems uses Queues to hold people
calling them in an order, until a service representative is free.
 Handling of interrupts in real-time systems. The interrupts are handled in the same
order as they arrive i.e First come first served.
 When a resource is shared among multiple consumers. Examples include Disk
Scheduling.
  When data is transferred asynchronously (data not necessarily received at same
rate as sent) between two processes. Examples include IO Buffers, pipes, file IO,
etc.
Conclusion 21

 Backtracking and (Stack and Queue) are very important algorithms corresponding
to solve complex problems of data structure and also in real life application.
 In N-Queen problem, we used backtracking in which we check for each row,
column and both diagonal. If in any position, the queens get attacked we used
backtracking to go to previous row or column to move queen so that each row or
column and row has one queen only.
 In Josephus problem, we used Stack and Queue through recurrence relation to get
one soldier at last who is winner of game. We used Stack and Queue to remove k th
soldier and rearrange the circle. In this way we get our winner.
References 22

 https://www.cis.upenn.edu/~matuszek/cit594-2012/Pages/backtracking.html
 https://www.geeksforgeeks.org/backtracking-introduction/
 https://www.codesdope.com/blog/article/backtracking-explanation-and-n-queens-
problem/
 youtube.com/watch?v=1OkZKjxRokU
 http://www.wisenheimerbrainstorm.com/archive/algorithms/josephus-problem-
using-a-queue
 https://www.youtube.com/watch?v=GKolKL51Mpw
 https://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/

You might also like