SlideShare a Scribd company logo
1 of 22
CHAPTER 4 Searching
Algorithm 4.1.1 Binary Search This algorithm searches for the value  key  in the nondecreasing array  L [ i ], ... , L[ j ]. If  key  is found, the algorithm returns an index  k  such that  L [ k ] equals  key . If  key  is not found, the algorithm returns -1, which is assumed not to be a valid index. Input Parameters:  L , i , j , key Output Parameters: None bsearch ( L , i , j , key ) { while ( i  =  j ) { k  = ( i  +  j )/2 if ( key  ==  L [ k ]) // found return  k if ( key  <  L [ k ]) // search first part j  =  k  - 1 else // search second part i  =  k  + 1 } return -1 // not found }
Algorithm 4.2.2 Depth-First Search This algorithm executes a depth-first search beginning at vertex start in a graph with vertices 1, ... ,  n  and outputs the vertices in the order in which they are visited. The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ver , the vertex adjacent to  i , and  next , the next node in the linked list or null, for the last node in the linked list. To track visited vertices, the algorithm uses an array  visit ;  visit[i ] is set to true if vertex  i  has been visited or to false if vertex  i  has not been visited.
Input Parameters:  adj , start Output Parameters: None dfs ( adj , start )  { n  =  adj . last for  i  = 1 to  n visit [ i ] = false dfs_recurs ( adj , start ) } dfs_recurs ( adj , start ) { println ( start ) visit [ start ] = true trav  =  adj [ start ] while ( trav  != null) { v  =  trav . ver if (! visit [ v ]) dfs_recurs ( adj , v ) trav  =  trav . next } }
Algorithm 4.3.2 Breadth-First Search This algorithm executes a breadth-first search beginning at vertex  start  in a graph with vertices 1, ... ,  n  and outputs the vertices in the order in which they are visited. The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ve r, the vertex adjacent to  i , and  next , a reference to the next node in the linked list or null, for the last node in the linked list. To track visited vertices, the algorithm uses an array  visit ;  visit [ i ] is set to true if vertex  i  has been visited or to false if vertex  i   has not been visited. The algorithm uses an initially empty queue  q  to store pending current vertices. The expression q . enqueue ( val ) adds  val  to  q . The expression q . front () returns the value at the front of  q  but does not remove it. The expression q . dequeue () removes the item at the front of  q . The expression q . empty () returns true if  q  is empty or false if  q  is not empty.
Input Parameters:  adj , start Output Parameters: None bfs ( adj , start )  { n  =  adj . last for  i  = 1 to  n visit [ i ] = false visit [ start ] = true println ( start ) q . enqueue ( start ) //  q  is an initially empty queue while (! q . empty ()) { current  =  q . front () q . dequeue () trav  =  adj [ current ] while ( trav  != null) { v  =  trav . ver if (! visit [ v ]) { visit [ v ] = true println ( v ) q . enqueue ( v ) } trav  =  trav . next } } }
Algorithm 4.3.4 Finding Shortest Path Lengths Using Breadth-First Search This algorithm finds the length of a shortest path from the start vertex  start to every other vertex in a graph with vertices 1, ... ,  n . The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ve r, the vertex adjacent to  i , and  next , a reference to the next node in the linked list or null, for the last node in the linked list. In the array  length ,  length [ i ] is set to the length of a shortest path from start to vertex  i  if this length has been computed or to  ∞  if the length has not been computed. If there is no path from start to  i , when the algorithm terminates,  length [ i ] is  ∞ .
Input Parameters:  adj , start Output Parameters:  length shortest_paths ( adj , start , length )  { n  =  adj . last for  i  = 1 to  n length [ i ] = ∞ length [ start ] = 0 q . enqueue ( start ) //  q  is an initially empty queue while (! q . empty ()) { current  =  q . front () q . dequeue () trav  =  adj [ current ] while ( trav  != null) { v  =  trav . ver if ( length [ v ] == ∞) { length [ v ] = 1 +  length [ current ]  q . enqueue ( v ) } trav  =  trav . next } } }
Algorithm 4.4.1 Topological Sort This algorithm computes a topological sort of a directed acyclic graph with vertices 1, ... ,  n .  The vertices in the topological sort are stored in the array  ts . The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ver , the vertex adjacent to  i , and  next , the next node in the linked list or null, for the last node in the linked list.  To track visited vertices, the algorithm uses an array  visit ;  visit[i ] is set to true if vertex  i  has been visited or to false if vertex  i   has not been visited.
Input Parameters:  adj Output Parameters:  ts top_sort ( adj , ts )  { n  =  adj . last //  k  is the index in  ts  where the next vertex is to be // stored in topological sort.  k  is assumed to be global. k  =  n for  i  = 1 to  n visit [ i ] = false for  i  = 1 to  n if (! visit [ v ]) top_sort_recurs ( adj , i , ts ) } top_sort_recurs ( adj , start , ts ) { visit [ start ] = true trav  =  adj [ start ] while ( trav  != null) { v  =  trav . ver if (! visit [ v ]) top_sort_recurs ( adj , v , ts ) trav  =  trav . next } ts [ k ] =  start k  =  k  - 1 }
Algorithm  n -Queens, Initial Version The  n -queens problem is to place n queens on an  n  ×  n  board so that no two queens are in the same row, column, or diagonal. Using backtracking, this algorithm outputs all solutions to this problem. We place queens successively in the columns beginning in the left column and working from top to bottom. When it is impossible to place a queen in a column, we return to the previous column and move its queen down.
n_queens ( n ) { rn_queens (1, n ) } rn_queens ( k , n ) { for  row [ k ] = 1 to  n if ( position_ok ( k , n )) if ( k  ==  n ) { for  i  = 1 to  n print ( row [ i ] + “ ”) println () } else rn_queens ( k  + 1, n ) } position_ok ( k , n ) for  i  = 1 to  k  - 1 //  abs  is absolute value if ( row [ k ] ==  row [ i ] ||  abs ( row [ k ] -  row [ i ]) ==  k  -  i ) return false return true }
Algorithm 4.5.2 Solving the  n -Queens Problem Using Backtracking The  n -queens problem is to place n queens on an  n  ×  n  board so that no two queens are in the same row, column, or diagonal. Using backtracking, this algorithm outputs all solutions to this problem. We place queens successively in the columns beginning in the left column and working from top to bottom. When it is impossible to place a queen in a column, we return to the previous column and move its queen down.
The value of  row [ k ] is the row where the queen in column  k  is placed. The algorithm begins when  n_queens  calls  rn_queens (1, n ). When rn_queens (k, n) is called, queens have been properly placed in columns 1 through  k  - 1, and rn_queens ( k , n ) tries to place a queen in column  k . If it is successful and  k equals  n , it prints a solution. If it is successful and  k  does not equal  n , it calls rn_queens ( k  + 1, n ). If it is not successful, it backtracks by returning to its caller rn_queens ( k  - 1 , n ). The value of  row_used [ r ] is true if a queen occupies row  r  and false otherwise. The value of  ddiag_used [ d ] is true if a queen occupies  ddiag  diagonal  d  and false otherwise. According to the numbering system used, the queen in column  k , row  r , is in  ddiag  diagonal  n  -  k  +  r . The value of  udiag_used [ d ] is true if a queen occupies  udiag  diagonal  d  and false otherwise. According to the numbering system used, the queen in column  k , row  r , is in  udiag   k  +  r  - 1. The function  position_ok ( k , n ) assumes that queens have been placed in columns 1 through  k  - 1. It returns true if the queen in column  k  does not conflict with the queens in columns 1 through  k - 1 or false if it does conflict.
Input Parameter:  n Output Parameters: None n_queens ( n ) { for  i  = 1 to  n row_used [ i ] = false for  i  = 1 to 2 *  n  - 1 ddiag_used [ i ] =  udiag_used [ i ] = false rn_queens (1, n ) } ...
... // When  rn_queens (k, n ) is called, queens have been // properly placed in columns 1 through  k  - 1. rn_queens ( k , n ) { for  row [ k ] = 1 to  n if ( position_ok ( k , n )) row_used [ row [ k ]] = true ddiag_used [ n  -  k  +  row [ k ]] = true udiag_used [ k  +  row [ k ] - 1] = true if ( k  ==  n ) { // Output a solution. Stop if only one  // solution is desired. for  i  = 1 to  n print ( row [ i ] + “ ”) println () } else rn_queens ( k  + 1, n ) row_used [ row [ k ]] = false ddiag_used [ n  -  k  +  row [ k ]] = false udiag_used [ k  +  row [ k ] - 1] = false } ...
... //  position_ok ( k , n ) returns true if the queen in column  k // does not conflict with the queens in columns 1 // through  k  - 1 or false if it does conflict. position_ok ( k , n ) return !( row_used [ row [ k ]] ||  ddiag_used [ n  -  k  +  row [ k ]] ||  udiag_used [ k  +  row [ k ] - 1 ]) }
Form of Backtracking Algorithm Suppose that we solve a problem using backtracking as in Algorithm 4.5.2 in which the solution is of the form  x [1], ... ,  x [ n ]. Suppose also that the values of  x [ i ] are in the set  S  (e.g., in Algorithm 4.5.2, S  = {1, . . . ,  n }).  We require a function  bound ( k ) with the following property. Whenever x [1], ... ,  x [ k  - 1] is a partial solution and  x [ k ] has been assigned a value, then  bound ( k ) has to return true if x [1], ... ,  x [ k ] is a partial solution and false otherwise. The key to writing a useful back- tracking algorithm is to write an efficient bound function that eliminates many potential nodes from the search tree.
The general form of a backtracking algorithm is backtrack(n) { rbacktrack(1,n) } rbacktrack(k,n) { for each x[k]    S if (bound(k)) if (k == n) { // Output a solution. Stop if only for i = 1 to n // one solution is desired. print(x[i] + “ ”) println() } else rbacktrack(k + 1, n) }
Algorithm 4.5.4 Searching for a Hamiltonian Cycle This algorithm inputs a graph with vertices 1, ... ,  n . The graph is represented as an adjacency matrix  adj ;  adj [ i ][ j ] is true if ( i , j ) is an edge or false if it is not an edge. If the graph has a Hamiltonian cycle, the algorithm computes one such cycle ( x [1], ... ,  x [ n ], x[1]). If the graph has no Hamiltonian cycle, the algorithm returns false and the contents of the array  x  are not specified. In the array  used ,  used [ i ] is true if  i  has been selected as one of the vertices in a potential Hamiltonian cycle or false if  i  has not been selected. The function  path_ok ( adj , k , x ) assumes that ( x [1], ... ,  x [ k  - 1]) is a path from  x [1] to  x [ k  - 1] and that the vertices  x [1], ... ,  x [ k  - 1] are distinct. It then checks whether  x [ k ] is different from each of  x [1], ... ,  x [ k  - 1] and whether ( x [ k  - 1],  x [ k ]) is an edge. If  k  =  n ,  path_ok  also checks whether ( x [ n ],  x [1]) is an edge.
Input Parameter:  adj Output Parameter:  x hamilton ( adj , x ) { n  =  adj . last x [1] = 1 used [1] = true for  i  = 2 to  n used [ i ] = false rhamilton ( adj ,2, x ) } rhamilton ( adj , k , x ) { n  =  adj . last for  x [ k ] = 2 to  n if ( path_ok ( adj , k , x )) { used [ x [ k ]] = true if ( k  ==  n  ||  rhamilton ( adj , k  + 1, x )) return true used [ x [ k ]] = false } return false } ...
... path_ok ( adj , k , x ) { n  =  adj . last if ( used [ x [ k ]]) return false if ( k  <  n ) return  adj [ x [ k  - 1]][ x [ k ]] else return  adj [ x [ n  - 1]][ x [ n ]] &&  adj [ x [1]][ x [ n ]] }

More Related Content

What's hot (20)

Sorting
SortingSorting
Sorting
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Lec2
Lec2Lec2
Lec2
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
 
Null space, Rank and nullity theorem
Null space, Rank and nullity theoremNull space, Rank and nullity theorem
Null space, Rank and nullity theorem
 
Merge sort
Merge sortMerge sort
Merge sort
 
Algorithm designing using divide and conquer algorithms
Algorithm designing using divide and conquer algorithmsAlgorithm designing using divide and conquer algorithms
Algorithm designing using divide and conquer algorithms
 
Eigenvalue problems .ppt
Eigenvalue problems .pptEigenvalue problems .ppt
Eigenvalue problems .ppt
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sorting
 
Presentation
PresentationPresentation
Presentation
 
Brute force
Brute forceBrute force
Brute force
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 
Eigenvectors & Eigenvalues: The Road to Diagonalisation
Eigenvectors & Eigenvalues: The Road to DiagonalisationEigenvectors & Eigenvalues: The Road to Diagonalisation
Eigenvectors & Eigenvalues: The Road to Diagonalisation
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
algorithm Unit 5
algorithm Unit 5 algorithm Unit 5
algorithm Unit 5
 
Sorting
SortingSorting
Sorting
 
algorithm Unit 3
algorithm Unit 3algorithm Unit 3
algorithm Unit 3
 
Deterministic finite automata
Deterministic finite automata Deterministic finite automata
Deterministic finite automata
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 

Viewers also liked

National Air And Space Museum Washington DC
National Air And Space Museum Washington DCNational Air And Space Museum Washington DC
National Air And Space Museum Washington DCShivakumar Patil
 
Was There A Darwinian Revolution
Was There A Darwinian RevolutionWas There A Darwinian Revolution
Was There A Darwinian RevolutionJohn Lynch
 
Google at a glance 1998 - 2008
Google at a glance 1998 - 2008Google at a glance 1998 - 2008
Google at a glance 1998 - 2008Andreas Jaffke
 
Why Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & ScienceWhy Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & ScienceJohn Lynch
 
History of Google Local from 2004-2011
History of Google Local from 2004-2011 History of Google Local from 2004-2011
History of Google Local from 2004-2011 Mike Blumenthal
 
A history of science (volume 1)
A history of science (volume 1) A history of science (volume 1)
A history of science (volume 1) Dipoceanov Esrever
 
Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"John Lynch
 
Ancient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionAncient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionJohn Lynch
 
The Scientific Revolution
The Scientific RevolutionThe Scientific Revolution
The Scientific RevolutionJohn Lynch
 
One Long Argument
One Long ArgumentOne Long Argument
One Long ArgumentJohn Lynch
 
History of Creationism, Parts II & III
History of Creationism, Parts II & IIIHistory of Creationism, Parts II & III
History of Creationism, Parts II & IIIJohn Lynch
 

Viewers also liked (20)

National Air And Space Museum Washington DC
National Air And Space Museum Washington DCNational Air And Space Museum Washington DC
National Air And Space Museum Washington DC
 
Ds 4
Ds 4Ds 4
Ds 4
 
Was There A Darwinian Revolution
Was There A Darwinian RevolutionWas There A Darwinian Revolution
Was There A Darwinian Revolution
 
Google at a glance 1998 - 2008
Google at a glance 1998 - 2008Google at a glance 1998 - 2008
Google at a glance 1998 - 2008
 
Why Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & ScienceWhy Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & Science
 
Google
GoogleGoogle
Google
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
CSS 3, Style and Beyond
CSS 3, Style and BeyondCSS 3, Style and Beyond
CSS 3, Style and Beyond
 
History of Google Local from 2004-2011
History of Google Local from 2004-2011 History of Google Local from 2004-2011
History of Google Local from 2004-2011
 
A history of science (volume 1)
A history of science (volume 1) A history of science (volume 1)
A history of science (volume 1)
 
Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"
 
simple-sorting algorithms
simple-sorting algorithmssimple-sorting algorithms
simple-sorting algorithms
 
sPen Data Management
sPen Data ManagementsPen Data Management
sPen Data Management
 
Ancient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionAncient Ideas of Creation & Evolution
Ancient Ideas of Creation & Evolution
 
The Scientific Revolution
The Scientific RevolutionThe Scientific Revolution
The Scientific Revolution
 
Chapter one
Chapter oneChapter one
Chapter one
 
One Long Argument
One Long ArgumentOne Long Argument
One Long Argument
 
Algorithms - Aaron Bloomfield
Algorithms - Aaron BloomfieldAlgorithms - Aaron Bloomfield
Algorithms - Aaron Bloomfield
 
History of Creationism, Parts II & III
History of Creationism, Parts II & IIIHistory of Creationism, Parts II & III
History of Creationism, Parts II & III
 
How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...
 

Similar to Chap04alg

N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cyclevarun arora
 
Graph applications chapter
Graph applications chapterGraph applications chapter
Graph applications chapterSavit Chandra
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptxSajalFayyaz
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02Abdul Samee
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxDeepakM509554
 
Skiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchSkiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchzukun
 

Similar to Chap04alg (20)

N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
Chap07alg
Chap07algChap07alg
Chap07alg
 
Chap07alg
Chap07algChap07alg
Chap07alg
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
 
Algo
AlgoAlgo
Algo
 
Graph applications chapter
Graph applications chapterGraph applications chapter
Graph applications chapter
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
 
Unit 4 jwfiles
Unit 4 jwfilesUnit 4 jwfiles
Unit 4 jwfiles
 
Chap12alg
Chap12algChap12alg
Chap12alg
 
Chap12alg
Chap12algChap12alg
Chap12alg
 
Chap11alg
Chap11algChap11alg
Chap11alg
 
Chap11alg
Chap11algChap11alg
Chap11alg
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Chap06alg
Chap06algChap06alg
Chap06alg
 
Chap06alg
Chap06algChap06alg
Chap06alg
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
 
Daa chapter11
Daa chapter11Daa chapter11
Daa chapter11
 
Skiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first searchSkiena algorithm 2007 lecture11 breadth deapth first search
Skiena algorithm 2007 lecture11 breadth deapth first search
 

More from Munkhchimeg (20)

Protsesor
ProtsesorProtsesor
Protsesor
 
Lecture916
Lecture916Lecture916
Lecture916
 
Lecture915
Lecture915Lecture915
Lecture915
 
Lecture914
Lecture914Lecture914
Lecture914
 
Lecture913
Lecture913Lecture913
Lecture913
 
Lecture911
Lecture911Lecture911
Lecture911
 
Lecture912
Lecture912Lecture912
Lecture912
 
Lecture910
Lecture910Lecture910
Lecture910
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture8
Lecture8Lecture8
Lecture8
 
Lecture7
Lecture7Lecture7
Lecture7
 
Lecture6
Lecture6Lecture6
Lecture6
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture3
Lecture3Lecture3
Lecture3
 
Ded Algorithm
Ded AlgorithmDed Algorithm
Ded Algorithm
 
Ded Algorithm1
Ded Algorithm1Ded Algorithm1
Ded Algorithm1
 
Tobch Lecture
Tobch LectureTobch Lecture
Tobch Lecture
 
Lecture914
Lecture914Lecture914
Lecture914
 
Tobch Lecture
Tobch LectureTobch Lecture
Tobch Lecture
 

Recently uploaded

2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideStefan Dietze
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...marcuskenyatta275
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfUK Journal
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 

Recently uploaded (20)

2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 

Chap04alg

  • 2. Algorithm 4.1.1 Binary Search This algorithm searches for the value key in the nondecreasing array L [ i ], ... , L[ j ]. If key is found, the algorithm returns an index k such that L [ k ] equals key . If key is not found, the algorithm returns -1, which is assumed not to be a valid index. Input Parameters: L , i , j , key Output Parameters: None bsearch ( L , i , j , key ) { while ( i = j ) { k = ( i + j )/2 if ( key == L [ k ]) // found return k if ( key < L [ k ]) // search first part j = k - 1 else // search second part i = k + 1 } return -1 // not found }
  • 3. Algorithm 4.2.2 Depth-First Search This algorithm executes a depth-first search beginning at vertex start in a graph with vertices 1, ... , n and outputs the vertices in the order in which they are visited. The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ver , the vertex adjacent to i , and next , the next node in the linked list or null, for the last node in the linked list. To track visited vertices, the algorithm uses an array visit ; visit[i ] is set to true if vertex i has been visited or to false if vertex i has not been visited.
  • 4. Input Parameters: adj , start Output Parameters: None dfs ( adj , start ) { n = adj . last for i = 1 to n visit [ i ] = false dfs_recurs ( adj , start ) } dfs_recurs ( adj , start ) { println ( start ) visit [ start ] = true trav = adj [ start ] while ( trav != null) { v = trav . ver if (! visit [ v ]) dfs_recurs ( adj , v ) trav = trav . next } }
  • 5. Algorithm 4.3.2 Breadth-First Search This algorithm executes a breadth-first search beginning at vertex start in a graph with vertices 1, ... , n and outputs the vertices in the order in which they are visited. The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ve r, the vertex adjacent to i , and next , a reference to the next node in the linked list or null, for the last node in the linked list. To track visited vertices, the algorithm uses an array visit ; visit [ i ] is set to true if vertex i has been visited or to false if vertex i has not been visited. The algorithm uses an initially empty queue q to store pending current vertices. The expression q . enqueue ( val ) adds val to q . The expression q . front () returns the value at the front of q but does not remove it. The expression q . dequeue () removes the item at the front of q . The expression q . empty () returns true if q is empty or false if q is not empty.
  • 6. Input Parameters: adj , start Output Parameters: None bfs ( adj , start ) { n = adj . last for i = 1 to n visit [ i ] = false visit [ start ] = true println ( start ) q . enqueue ( start ) // q is an initially empty queue while (! q . empty ()) { current = q . front () q . dequeue () trav = adj [ current ] while ( trav != null) { v = trav . ver if (! visit [ v ]) { visit [ v ] = true println ( v ) q . enqueue ( v ) } trav = trav . next } } }
  • 7. Algorithm 4.3.4 Finding Shortest Path Lengths Using Breadth-First Search This algorithm finds the length of a shortest path from the start vertex start to every other vertex in a graph with vertices 1, ... , n . The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ve r, the vertex adjacent to i , and next , a reference to the next node in the linked list or null, for the last node in the linked list. In the array length , length [ i ] is set to the length of a shortest path from start to vertex i if this length has been computed or to ∞ if the length has not been computed. If there is no path from start to i , when the algorithm terminates, length [ i ] is ∞ .
  • 8. Input Parameters: adj , start Output Parameters: length shortest_paths ( adj , start , length ) { n = adj . last for i = 1 to n length [ i ] = ∞ length [ start ] = 0 q . enqueue ( start ) // q is an initially empty queue while (! q . empty ()) { current = q . front () q . dequeue () trav = adj [ current ] while ( trav != null) { v = trav . ver if ( length [ v ] == ∞) { length [ v ] = 1 + length [ current ] q . enqueue ( v ) } trav = trav . next } } }
  • 9. Algorithm 4.4.1 Topological Sort This algorithm computes a topological sort of a directed acyclic graph with vertices 1, ... , n . The vertices in the topological sort are stored in the array ts . The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ver , the vertex adjacent to i , and next , the next node in the linked list or null, for the last node in the linked list. To track visited vertices, the algorithm uses an array visit ; visit[i ] is set to true if vertex i has been visited or to false if vertex i has not been visited.
  • 10. Input Parameters: adj Output Parameters: ts top_sort ( adj , ts ) { n = adj . last // k is the index in ts where the next vertex is to be // stored in topological sort. k is assumed to be global. k = n for i = 1 to n visit [ i ] = false for i = 1 to n if (! visit [ v ]) top_sort_recurs ( adj , i , ts ) } top_sort_recurs ( adj , start , ts ) { visit [ start ] = true trav = adj [ start ] while ( trav != null) { v = trav . ver if (! visit [ v ]) top_sort_recurs ( adj , v , ts ) trav = trav . next } ts [ k ] = start k = k - 1 }
  • 11. Algorithm n -Queens, Initial Version The n -queens problem is to place n queens on an n × n board so that no two queens are in the same row, column, or diagonal. Using backtracking, this algorithm outputs all solutions to this problem. We place queens successively in the columns beginning in the left column and working from top to bottom. When it is impossible to place a queen in a column, we return to the previous column and move its queen down.
  • 12. n_queens ( n ) { rn_queens (1, n ) } rn_queens ( k , n ) { for row [ k ] = 1 to n if ( position_ok ( k , n )) if ( k == n ) { for i = 1 to n print ( row [ i ] + “ ”) println () } else rn_queens ( k + 1, n ) } position_ok ( k , n ) for i = 1 to k - 1 // abs is absolute value if ( row [ k ] == row [ i ] || abs ( row [ k ] - row [ i ]) == k - i ) return false return true }
  • 13. Algorithm 4.5.2 Solving the n -Queens Problem Using Backtracking The n -queens problem is to place n queens on an n × n board so that no two queens are in the same row, column, or diagonal. Using backtracking, this algorithm outputs all solutions to this problem. We place queens successively in the columns beginning in the left column and working from top to bottom. When it is impossible to place a queen in a column, we return to the previous column and move its queen down.
  • 14. The value of row [ k ] is the row where the queen in column k is placed. The algorithm begins when n_queens calls rn_queens (1, n ). When rn_queens (k, n) is called, queens have been properly placed in columns 1 through k - 1, and rn_queens ( k , n ) tries to place a queen in column k . If it is successful and k equals n , it prints a solution. If it is successful and k does not equal n , it calls rn_queens ( k + 1, n ). If it is not successful, it backtracks by returning to its caller rn_queens ( k - 1 , n ). The value of row_used [ r ] is true if a queen occupies row r and false otherwise. The value of ddiag_used [ d ] is true if a queen occupies ddiag diagonal d and false otherwise. According to the numbering system used, the queen in column k , row r , is in ddiag diagonal n - k + r . The value of udiag_used [ d ] is true if a queen occupies udiag diagonal d and false otherwise. According to the numbering system used, the queen in column k , row r , is in udiag k + r - 1. The function position_ok ( k , n ) assumes that queens have been placed in columns 1 through k - 1. It returns true if the queen in column k does not conflict with the queens in columns 1 through k - 1 or false if it does conflict.
  • 15. Input Parameter: n Output Parameters: None n_queens ( n ) { for i = 1 to n row_used [ i ] = false for i = 1 to 2 * n - 1 ddiag_used [ i ] = udiag_used [ i ] = false rn_queens (1, n ) } ...
  • 16. ... // When rn_queens (k, n ) is called, queens have been // properly placed in columns 1 through k - 1. rn_queens ( k , n ) { for row [ k ] = 1 to n if ( position_ok ( k , n )) row_used [ row [ k ]] = true ddiag_used [ n - k + row [ k ]] = true udiag_used [ k + row [ k ] - 1] = true if ( k == n ) { // Output a solution. Stop if only one // solution is desired. for i = 1 to n print ( row [ i ] + “ ”) println () } else rn_queens ( k + 1, n ) row_used [ row [ k ]] = false ddiag_used [ n - k + row [ k ]] = false udiag_used [ k + row [ k ] - 1] = false } ...
  • 17. ... // position_ok ( k , n ) returns true if the queen in column k // does not conflict with the queens in columns 1 // through k - 1 or false if it does conflict. position_ok ( k , n ) return !( row_used [ row [ k ]] || ddiag_used [ n - k + row [ k ]] || udiag_used [ k + row [ k ] - 1 ]) }
  • 18. Form of Backtracking Algorithm Suppose that we solve a problem using backtracking as in Algorithm 4.5.2 in which the solution is of the form x [1], ... , x [ n ]. Suppose also that the values of x [ i ] are in the set S (e.g., in Algorithm 4.5.2, S = {1, . . . , n }). We require a function bound ( k ) with the following property. Whenever x [1], ... , x [ k - 1] is a partial solution and x [ k ] has been assigned a value, then bound ( k ) has to return true if x [1], ... , x [ k ] is a partial solution and false otherwise. The key to writing a useful back- tracking algorithm is to write an efficient bound function that eliminates many potential nodes from the search tree.
  • 19. The general form of a backtracking algorithm is backtrack(n) { rbacktrack(1,n) } rbacktrack(k,n) { for each x[k]  S if (bound(k)) if (k == n) { // Output a solution. Stop if only for i = 1 to n // one solution is desired. print(x[i] + “ ”) println() } else rbacktrack(k + 1, n) }
  • 20. Algorithm 4.5.4 Searching for a Hamiltonian Cycle This algorithm inputs a graph with vertices 1, ... , n . The graph is represented as an adjacency matrix adj ; adj [ i ][ j ] is true if ( i , j ) is an edge or false if it is not an edge. If the graph has a Hamiltonian cycle, the algorithm computes one such cycle ( x [1], ... , x [ n ], x[1]). If the graph has no Hamiltonian cycle, the algorithm returns false and the contents of the array x are not specified. In the array used , used [ i ] is true if i has been selected as one of the vertices in a potential Hamiltonian cycle or false if i has not been selected. The function path_ok ( adj , k , x ) assumes that ( x [1], ... , x [ k - 1]) is a path from x [1] to x [ k - 1] and that the vertices x [1], ... , x [ k - 1] are distinct. It then checks whether x [ k ] is different from each of x [1], ... , x [ k - 1] and whether ( x [ k - 1], x [ k ]) is an edge. If k = n , path_ok also checks whether ( x [ n ], x [1]) is an edge.
  • 21. Input Parameter: adj Output Parameter: x hamilton ( adj , x ) { n = adj . last x [1] = 1 used [1] = true for i = 2 to n used [ i ] = false rhamilton ( adj ,2, x ) } rhamilton ( adj , k , x ) { n = adj . last for x [ k ] = 2 to n if ( path_ok ( adj , k , x )) { used [ x [ k ]] = true if ( k == n || rhamilton ( adj , k + 1, x )) return true used [ x [ k ]] = false } return false } ...
  • 22. ... path_ok ( adj , k , x ) { n = adj . last if ( used [ x [ k ]]) return false if ( k < n ) return adj [ x [ k - 1]][ x [ k ]] else return adj [ x [ n - 1]][ x [ n ]] && adj [ x [1]][ x [ n ]] }