mirror of
https://github.com/mfocko/blog.git
synced 2024-11-14 01:59:42 +01:00
1 line
No EOL
13 KiB
JavaScript
1 line
No EOL
13 KiB
JavaScript
"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[569],{64322:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>r,default:()=>m,frontMatter:()=>a,metadata:()=>o,toc:()=>h});var s=n(85893),i=n(11151);const a={id:"iterative-and-iterators",title:"Iterative algorithms via iterators",description:"Iterative DFS using iterators.\n",tags:["csharp","graphs","iterators","iterative"],last_update:{date:new Date("2021-05-18T00:00:00.000Z")}},r=void 0,o={id:"graphs/iterative-and-iterators",title:"Iterative algorithms via iterators",description:"Iterative DFS using iterators.\n",source:"@site/algorithms/10-graphs/2021-05-18-iterative-and-iterators.md",sourceDirName:"10-graphs",slug:"/graphs/iterative-and-iterators",permalink:"/algorithms/graphs/iterative-and-iterators",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/algorithms/10-graphs/2021-05-18-iterative-and-iterators.md",tags:[{label:"csharp",permalink:"/algorithms/tags/csharp"},{label:"graphs",permalink:"/algorithms/tags/graphs"},{label:"iterators",permalink:"/algorithms/tags/iterators"},{label:"iterative",permalink:"/algorithms/tags/iterative"}],version:"current",lastUpdatedAt:1621296e3,formattedLastUpdatedAt:"May 18, 2021",frontMatter:{id:"iterative-and-iterators",title:"Iterative algorithms via iterators",description:"Iterative DFS using iterators.\n",tags:["csharp","graphs","iterators","iterative"],last_update:{date:"2021-05-18T00:00:00.000Z"}},sidebar:"autogeneratedBar",previous:{title:"Graphs",permalink:"/algorithms/category/graphs"},next:{title:"Distance boundaries from BFS tree on undirected graphs",permalink:"/algorithms/graphs/bfs-tree"}},c={},h=[{value:"Introduction",id:"introduction",level:2},{value:"Different implementations",id:"different-implementations",level:2},{value:"Recursive DFS implementation from exercises without colors",id:"recursive-dfs-implementation-from-exercises-without-colors",level:3},{value:"Iterative DFS from the exercises",id:"iterative-dfs-from-the-exercises",level:3},{value:"My iterative with path in stack",id:"my-iterative-with-path-in-stack",level:3},{value:"My iterative solution with iterators",id:"my-iterative-solution-with-iterators",level:3},{value:"Implementation",id:"implementation",level:2}];function l(e){const t={a:"a",annotation:"annotation",code:"code",em:"em",h2:"h2",h3:"h3",li:"li",math:"math",mi:"mi",mo:"mo",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",ul:"ul",...(0,i.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(t.h2,{id:"introduction",children:"Introduction"}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"pathname:///files/algorithms/graphs/iterative-and-iterators.tar.gz",children:"Source code used later on."})}),"\n"]}),"\n",(0,s.jsx)(t.p,{children:"As we have talked on the seminar, iterative approach to implementing DFS is not very intuitive and is a very easy way how to create an incorrect implementation."}),"\n",(0,s.jsx)(t.p,{children:"On the other hand, we have seen iterative implementation in the exercises and I have also prepared two from which one was similar to recursive implementation without colors from exercises and the other one used features of high-level languages."}),"\n",(0,s.jsx)(t.h2,{id:"different-implementations",children:"Different implementations"}),"\n",(0,s.jsx)(t.h3,{id:"recursive-dfs-implementation-from-exercises-without-colors",children:"Recursive DFS implementation from exercises without colors"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ada",metastring:"showLineNumbers",children:"function VisitedDFS(u: Vertex, visited: VertexSet) return VertexSet is\n v: Vertex;\nbegin\n visited.Union(To_Set(u));\n\n for v in u.successors loop\n if not Contains(visited, v) then\n visited := visitedDFS(v, Visited);\n end if;\n end loop;\n\n return visited;\nend VisitedDFS;\n"})}),"\n",(0,s.jsxs)(t.p,{children:["This implementation is correct, does the DFS traversal as it should, however it has one \u201csmallish\u201d downside and that is the time complexity. The usage of set raises the time complexity, of course it is implementation dependant. However in case of either RB-tree or hash-table implementation, we get look-up in time ",(0,s.jsxs)(t.span,{className:"katex",children:[(0,s.jsx)(t.span,{className:"katex-mathml",children:(0,s.jsx)(t.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,s.jsxs)(t.semantics,{children:[(0,s.jsxs)(t.mrow,{children:[(0,s.jsx)(t.mi,{mathvariant:"script",children:"O"}),(0,s.jsx)(t.mo,{stretchy:"false",children:"("}),(0,s.jsx)(t.mi,{children:"n"}),(0,s.jsx)(t.mo,{stretchy:"false",children:")"})]}),(0,s.jsx)(t.annotation,{encoding:"application/x-tex",children:"\\mathcal{O}(n)"})]})})}),(0,s.jsx)(t.span,{className:"katex-html","aria-hidden":"true",children:(0,s.jsxs)(t.span,{className:"base",children:[(0,s.jsx)(t.span,{className:"strut",style:{height:"1em",verticalAlign:"-0.25em"}}),(0,s.jsx)(t.span,{className:"mord mathcal",style:{marginRight:"0.02778em"},children:"O"}),(0,s.jsx)(t.span,{className:"mopen",children:"("}),(0,s.jsx)(t.span,{className:"mord mathnormal",children:"n"}),(0,s.jsx)(t.span,{className:"mclose",children:")"})]})})]})," for hash-table in worst-case or ",(0,s.jsxs)(t.span,{className:"katex",children:[(0,s.jsx)(t.span,{className:"katex-mathml",children:(0,s.jsx)(t.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,s.jsxs)(t.semantics,{children:[(0,s.jsxs)(t.mrow,{children:[(0,s.jsx)(t.mi,{mathvariant:"script",children:"O"}),(0,s.jsx)(t.mo,{stretchy:"false",children:"("}),(0,s.jsx)(t.mi,{children:"log"}),(0,s.jsx)(t.mo,{children:"\u2061"}),(0,s.jsx)(t.mi,{children:"n"}),(0,s.jsx)(t.mo,{stretchy:"false",children:")"})]}),(0,s.jsx)(t.annotation,{encoding:"application/x-tex",children:"\\mathcal{O}(\\log n)"})]})})}),(0,s.jsx)(t.span,{className:"katex-html","aria-hidden":"true",children:(0,s.jsxs)(t.span,{className:"base",children:[(0,s.jsx)(t.span,{className:"strut",style:{height:"1em",verticalAlign:"-0.25em"}}),(0,s.jsx)(t.span,{className:"mord mathcal",style:{marginRight:"0.02778em"},children:"O"}),(0,s.jsx)(t.span,{className:"mopen",children:"("}),(0,s.jsxs)(t.span,{className:"mop",children:["lo",(0,s.jsx)(t.span,{style:{marginRight:"0.01389em"},children:"g"})]}),(0,s.jsx)(t.span,{className:"mspace",style:{marginRight:"0.1667em"}}),(0,s.jsx)(t.span,{className:"mord mathnormal",children:"n"}),(0,s.jsx)(t.span,{className:"mclose",children:")"})]})})]})," for the other in the worst-case. Both are not ideal compared to checking color on vertex."]}),"\n",(0,s.jsx)(t.h3,{id:"iterative-dfs-from-the-exercises",children:"Iterative DFS from the exercises"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ada",metastring:"showLineNumbers",children:"procedure IterDFS(u: Vertex) is\n stack: StateVector;\n i, time: Integer;\n v: Vertex;\nbegin\n stack.Append(VertexState(u, 0));\n u.color := Gray;\n time := 1;\n u.d := time;\n\n while not stack.Is_Empty loop\n u := stack.Last_Element.Vertex;\n i := stack.Last_Element.NextIndex;\n stack.Delete_Last;\n\n if i < u.successors.Length then\n -- search is not finished, is pushed back to stack\n stack.Append(VertexState(u, k + 1));\n\n v := u.successors.Element(i);\n if v.color = White then\n stack.Append(VertexState(v, 0));\n v.color := Gray;\n time := time + 1;\n v.d := time;\n end if;\n else\n -- u has no other successors, we can finish the search\n time := time + 1;\n u.f := time;\n u.color := Black;\n end if;\n end loop;\n\nend IterDFS;\n"})}),"\n",(0,s.jsx)(t.p,{children:"As we can see, there is some ordering in which we search through the successors. Time complexity is OK, stack holds at most all vertices (they must be on the current path)."}),"\n",(0,s.jsx)(t.h3,{id:"my-iterative-with-path-in-stack",children:"My iterative with path in stack"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ada",metastring:"showLineNumbers",children:"procedure DFS(start: Vertex) is\n path: VertexVector;\n time: Integer;\n hasSuccessor: Bool;\n successor: Vertex;\nbegin\n path.Append(start);\n time := 1;\n\n start.d := time;\n start.color := Gray;\n\n while not path.Is_Empty loop\n hasSuccessor := false;\n\n for successor in path.Last_Element.successors loop\n if successor.color = White then\n hasSuccessor := true;\n\n successor.d := time + 1;\n successor.color := Gray;\n time := time + 1;\n\n path.Append(successor);\n\n exit;\n end if;\n end loop;\n\n if not hasSuccessor then\n path.Last_Element.f := time + 1;\n path.Last_Element.color := Black;\n\n time := time + 1;\n path.Delete_Last;\n end if;\n\n end loop;\nend DFS;\n"})}),"\n",(0,s.jsx)(t.p,{children:"This approach is similar to the iterative solution from the exercises, but it does not keep the index of the next successor, therefore it always iterates through all of them, which raises the time complexity."}),"\n",(0,s.jsx)(t.h3,{id:"my-iterative-solution-with-iterators",children:"My iterative solution with iterators"}),"\n",(0,s.jsxs)(t.p,{children:["On the other hand, we do not actually have to depend on the representation of the graph. In this case, we just ",(0,s.jsx)(t.em,{children:"somehow"})," obtain the iterator (which yields all of the succesors) and keep it in the stack."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ada",metastring:"showLineNumbers",children:"procedure DFS(start: Vertex) is\n path: StateVector;\n time: Integer;\n current: State;\n nextVertex: Vertex;\nbegin\n path.Append(State(start));\n time := 1;\n\n start.d := time;\n start.color := Gray;\n\n while not path.Is_Empty loop\n current := path.Last_Element;\n\n if not Move_Next(current.successors) then\n path.Delete_Last;\n\n time := time + 1;\n current.vertex.f := time;\n\n current.vertex.color := Black;\n else if current.successors.Value.color = white then\n nextVertex := current.successors.Value;\n\n time := time + 1;\n nextVertex.d := time;\n\n nextVertex.color := Gray;\n\n path.Append(State(nextVertex));\n end if;\n end loop;\nend DFS;\n"})}),"\n",(0,s.jsxs)(t.p,{children:["( The way we manipulate with the iterators is closest to the C# implementation. Apart from the ",(0,s.jsx)(t.code,{children:"Iterator"})," thing :) In case you tried to implement it in C++, you would more than likely need to change the check, since you would get first successor right at the beginning )"]}),"\n",(0,s.jsx)(t.p,{children:"So here we don't keep indices, but the iterators. We can also check existence of other successors easily: by the iterator moving after the last successor."}),"\n",(0,s.jsxs)(t.p,{children:["Closer explanation of the ",(0,s.jsx)(t.em,{children:"iterator shenanigans"})," follows. In the beginning, either ",(0,s.jsx)(t.code,{children:"start"})," or when pushing new vertex, we are pushing an iterator that points ",(0,s.jsx)(t.em,{children:"just before"})," the first successor. When populating ",(0,s.jsx)(t.code,{children:"lastVertex"})," and ",(0,s.jsx)(t.code,{children:"successors"})," in the ",(0,s.jsx)(t.code,{children:"while"}),"-loop, we take the element from the top of the stack. ",(0,s.jsx)(t.code,{children:"MoveNext"})," returns ",(0,s.jsx)(t.code,{children:"true"})," if there is an element, i.e. successor in this case. If it returns ",(0,s.jsx)(t.code,{children:"false"})," we have nothing to do and we pop the vertex from the stack (also set finishing time and color). If we have successor we check if it has been already visited or not. If has not, we set discovery time and color accordingly, also we add it to stack."]}),"\n",(0,s.jsx)(t.h2,{id:"implementation",children:"Implementation"}),"\n",(0,s.jsx)(t.p,{children:"In case you want to play around with the code. At the beginning there is a link to the C# implementation that can be used. It has a basic representation of graph and includes BFS/DFS implementation in classes."}),"\n",(0,s.jsxs)(t.p,{children:["In ",(0,s.jsx)(t.code,{children:"Program.cs"})," you can also find a method that returns graph we used on the seminar."]})]})}function m(e={}){const{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,s.jsx)(t,{...e,children:(0,s.jsx)(l,{...e})}):l(e)}},11151:(e,t,n)=>{n.d(t,{Z:()=>o,a:()=>r});var s=n(67294);const i={},a=s.createContext(i);function r(e){const t=s.useContext(a);return s.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function o(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:r(e.components),s.createElement(a.Provider,{value:t},e.children)}}}]); |