APPLICATION OF STACK:
BACKTRACKING
BACKTRACKING
Backtracking is a method to find a proper path to
some certain goal, from a number of the ones.
This method is widely used in decision analysis,
expert systems and computer gaming.
Goal seeking is a typical backtracking algorithm
of finding the unique path to a desired goal.
BACKTRACKING
Suppose you have to make a series of decisions,
among various choices, where
You don’t have enough information to know what to choose
Each decision leads to a new set of choices
Some sequence of choices (possibly more than one) may be a solution to your problem
Backtracking is a methodical way of trying out
various sequences of decisions, until you find
one that “works”
COMMON IDEA OF BACKTRACKING
In solving some problems, from a given position, there are some available valid paths to go.
Only one path may be try at a time.
Others are the backtracking points to try later.
If one valid path is ended without desired solution, backtracking allows trying through another paths systematically.
Backtracking is very suitable for problems need to find out all solutions.
Every time one solution is found, it’s saved somewhere, and backtracking allows continuing for the rest.
APPLICATION OF BACKTRACKING:
COLORING A MAP
You wish to color a map with not more than four colors
red, yellow, green, blue
Adjacent countries must be in different colors
You don’t have enough information to choose colors Each choice leads to another set of choices
One or more sequences of choices may (or may not) lead to a solution
Many coloring problems can be solved with backtracking
APPLICATION OF BACKTRACKING:
APPLICATION OF BACKTRACKING:
SOLVING A MAZE
Given a maze, find a path from start to finish
At each intersection, you have to decide between
three or fewer choices:
Go straight Go left
Go right
You don’t have enough information to choose correctly Each choice leads to another set of choices
One or more sequences of choices may (or may not) lead to a solution
Many types of maze problem can be solved with backtracking
APPLICATION OF BACKTRACKING:
GOAL SEEKING PROBLEM
Find the path from the start node to the destination.
Various complexity and extension of goal seeking problem: •Having only one start node and one destination.
•Having one start node and some destinations.
•Need to determine whether the path exists or not. •If the path exists, show the nodes in it.
•Need to determine the cost of the path.
•The cost of the path will answer the problem not the specific destinations
•Find only one result if exists. •Find out all results if exist.
Precondition:
Acyclic Graph as StartNode
and Destination.
Post condition:
Determine whether the path
from Start Node to Destination exists or not.
TERMINOLOGY I
10
There are three kinds of nodes: A tree is composed of nodes
The (one) root node
Internal nodes
Leaf nodes
Backtracking can be thought of as
searching a tree for a particular “goal” leaf node
TERMINOLOGY II
Each non-leaf node in a tree is a parent of one or
more other nodes (its children)
Each node in the tree, other than the root, has
exactly one parent
11 parent children parent children Usually, however, we
draw our trees
downward, with the
THE BACKTRACKING ALGORITHM
Backtracking is really quite simple--we “explore”
each node, as follows:
To “explore” node N:
● 1. If N is a goal node, return “success”
● 2. If N is a leaf node, return “failure”
● 3. For each child C of N,
● 3.1. Explore C
● 3.1.1. If C was successful, return “success”
● 4. Return “failure”
SIMPLE EXAMPLE OF BACKTRACKING (GOAL SEEKING) 1 2 3 4 12 5 6 7 8 9 10 11 13 14 15 16 17 18 Start node B12 3 2 1 B8 B9 5 4 B12 3 2 1 End 7 6 B8 B9 5 4 B12 3 2 1 End 8 B9 5 4 B12 3 2 1 End 11 10 9 5 4 B12 3 2 1 Goa l 16 15 14 B17 13 12 3 2 1 (a) (b) (c ) (d) (e ) (f)
*
15
PATH TO
GOAL
Algorithm seekGoal (val map <linked list>)
This algorithm determines the path to a desired goal.
Pre a graph containing the path Post path printed
1 Stack=createStack
2 Set pMap to starting point
3 loop (pMap not null AND goalNotFound) 1 if (pMap is goal)
1 set goalNoFound to false 2 else
1 pushStack (stack,pMap) 2 if (pMapis a branch point)
1 loop (more branch point) 1 create branchPoint node
2 pushStack (stack, branchPoint) 3 advance to next node
4 if (emptyStack (stack))
1 print (There is no path to your goal) 5 else
1 print (The path to your goal is: ) 2 loop (not emptyStack (stack))
1 popStack (stack, pMap) 2 if (pMap notbranchPoint) 1 print (pMAp->nodeName) 3 print (End of File)
6 destroyStack (stack)
REVERSE STRING /LIST
We can accomplish this by pushing each
character or member from the string/ list in the
order it appears.
When the line is finished, characters are then
popped off the stack.
PROGRAM TO REVERSE A STRING
USING STACK
typedef struct stack {
char b[100]; int top;
}stack;
void push(stack *s,char k) {
if(s->top==99)
printf("\n Stack is full "); else
s->b[++s->top]=k; }
PROGRAM TO REVERSE A STRING
USING STACK
char pop(stack *s) { char c; if(s->top==(-1))printf("\n Stack is empty"); else
{
c=s->b[s->top--]; return c;
PROGRAM TO REVERSE A STRING USING
STACK
void main() { char name[100]; stack s; clrscr(); s.top=-1; printf("\nEnter name :"); gets(name); int i=0; while(name[i]!='\0') { push(&s,name[i]); i++; }printf("\n Reverse string is :"); while(s.top!=-1) { printf("%c",pop(&s)); } getch(); }
PALINDROME EXAMPLE
The strings where the reading from the reverse and forward directions give the same word are called a palindrome. For example, the string ”radar” is an example for palindrome.
Among many other techniques stack can be used to determine if a string is a palindrome or not. This is achieved by pushing all the letters of a given word into stack and checking if the letters popped are the same as the letter of the string.
Write a program using stack to determine whether a given string is a palindrome or not?
PROGRAM TO CHECK WHTHER THE
GIVEN STRING IS PALINDROME OR NOT?
#include <stdio.h> #include <stdlib.h> #include <conio.h> #define SIZE 10 typedef struct { int items[SIZE]; int top; }STACK; void push(); int pop();
int main() { STACK s; char str[100]; int i, flag; s.top = -1; printf("\nEnter a string: "); gets(str); for(i=0;str[i]!='\0'; i++) push(&s, str[i]);
flag = 1; for(i=0;str[i]!='\0';i++) { if(str[i] != pop(&s)) { flag = 0; break; } } if(flag == 1)
printf("\nEntered string is palindrome\n"); else
printf("\nEntered string is not a palindrome\n"); }
void push(STACK *p, int element) { if(p->top==size -1) { printf("\nStack is overflow"); } else { (p->top)++; p->items[p->top] = element; } }
int pop(STACK *p) { if(p->top==-1) { printf("\nStack is underflow"); } else { return (p->items[(p->top)--]); } }
29
CHECKING FOR BALANCED BRACES
■
A stack can be used to verify whether a
program contains balanced braces
❑ An example of balanced braces
■ abc{defg{ijk}{l{mn}}op}qr
❑ An example of unbalanced braces
30
CHECKING FOR BALANCED
BRACES
■
Requirements for balanced braces
❑ Each time you encounter a “}”, it matches an already encountered “{”
❑ When you reach the end of the string, you have matched each “{”
31
Checking for Balanced Braces
Figure 6-3
STACK APPLICATIONS: CONVERTING DECIMAL TO BINARY:
Converting Decimal to Binary: Consider the following pseudocode 1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2 2) print (digit)
3) number = number / 2
The problem with this code is that it will print the binary
number backwards. (ex: 19 becomes 11001000 instead of 00010011. ) To remedy this problem, instead of printing the digit right away,
we can push it onto the stack.
Then after the number is done being converted, we pop the digit out of the stack and print it.
PROBLEM.
DECIMAL-TO-BINARY CONVERSIONproblem.
Decimal-to-Binary Conversion
void main() {
stack s; int num; s.top=-1;
printf("\nEnter decimal number:"); scanf("%d",&num); while((num!=0)) { push(&s,num%2); num=num/2; }