Find a path from s to t using as few red nodes as possible The Next CEO of Stack OverflowDijkstra algorithm vs breadth first search for shortest path in graphAlgorithm to find diameter of a tree using BFS/DFS. Why does it work?Finding shortest path from a node to any node of a particular typeParallel algorithm to find if a set of nodes is on an elememtry cycle in a directed/undirected graphShortest path in unweighted graph using an iterator onlyShortest Path using DFS on weighted graphsCan a 3 Color DFS be used to identify cycles (not just detect them)?Find a path that contains specific nodes without back and forward edgesChecking if there is a single path that visits all nodes in a directed graphFind shortest path that goes through at least 5 red edges

How dangerous is XSS

Finitely generated matrix groups whose eigenvalues are all algebraic

How can the PCs determine if an item is a phylactery?

Gauss' Posthumous Publications?

How to find if SQL server backup is encrypted with TDE without restoring the backup

Direct Implications Between USA and UK in Event of No-Deal Brexit

Does int main() need a declaration on C++?

Calculate the Mean mean of two numbers

Words hidden in my phone number

My boss doesn't want me to have a side project

It it possible to avoid kiwi.com's automatic online check-in and instead do it manually by yourself?

Why does freezing point matter when picking cooler ice packs?

A hang glider, sudden unexpected lift to 25,000 feet altitude, what could do this?

Could a dragon use its wings to swim?

Can I cast Thunderwave and be at the center of its bottom face, but not be affected by it?

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

Is a linearly independent set whose span is dense a Schauder basis?

How does a dynamic QR code work?

The sum of any ten consecutive numbers from a fibonacci sequence is divisible by 11

How should I connect my cat5 cable to connectors having an orange-green line?

Could you use a laser beam as a modulated carrier wave for radio signal?

Ising model simulation

Raspberry pi 3 B with Ubuntu 18.04 server arm64: what pi version

Calculating discount not working



Find a path from s to t using as few red nodes as possible



The Next CEO of Stack OverflowDijkstra algorithm vs breadth first search for shortest path in graphAlgorithm to find diameter of a tree using BFS/DFS. Why does it work?Finding shortest path from a node to any node of a particular typeParallel algorithm to find if a set of nodes is on an elememtry cycle in a directed/undirected graphShortest path in unweighted graph using an iterator onlyShortest Path using DFS on weighted graphsCan a 3 Color DFS be used to identify cycles (not just detect them)?Find a path that contains specific nodes without back and forward edgesChecking if there is a single path that visits all nodes in a directed graphFind shortest path that goes through at least 5 red edges










2












$begingroup$


Was doing a little interview prep. Given an undirected graph G, such that each node is colored red or blue and |E|≥|V|, find a path in O(|E|) time such that starting and ending at 2 blue nodes, s and t, that you pass through as few red nodes as possible.



Initial Impressions: Since |E|≥|V|, O(|E|) time would include O(|E|+|V|), which means the solution likely uses BFS or DFS. Modifying the graph such that causing the all red nodes must be forced down a directed path of some long length (after making the whole graph directed) in order to use out-of-the-box BFS seems not viable, as it would mean constructing a new graph would be along O(|E||V|) time.



Another method I toyed around with was propagating values to nodes based on the safest path to that node while doing a DFS search, but not all values were guaranteed to update.



I still want to try to solve this myself, but I'm really stuck right now. Was wondering if there were any hints I could get. There are much simpler ways of doing this if it weren't for the O(|E|) time. Djikstras with creating some edge weights would work, but wouldn't be within the time bound.










share|cite|improve this question









$endgroup$







  • 1




    $begingroup$
    Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
    $endgroup$
    – Yuval Filmus
    2 hours ago















2












$begingroup$


Was doing a little interview prep. Given an undirected graph G, such that each node is colored red or blue and |E|≥|V|, find a path in O(|E|) time such that starting and ending at 2 blue nodes, s and t, that you pass through as few red nodes as possible.



Initial Impressions: Since |E|≥|V|, O(|E|) time would include O(|E|+|V|), which means the solution likely uses BFS or DFS. Modifying the graph such that causing the all red nodes must be forced down a directed path of some long length (after making the whole graph directed) in order to use out-of-the-box BFS seems not viable, as it would mean constructing a new graph would be along O(|E||V|) time.



Another method I toyed around with was propagating values to nodes based on the safest path to that node while doing a DFS search, but not all values were guaranteed to update.



I still want to try to solve this myself, but I'm really stuck right now. Was wondering if there were any hints I could get. There are much simpler ways of doing this if it weren't for the O(|E|) time. Djikstras with creating some edge weights would work, but wouldn't be within the time bound.










share|cite|improve this question









$endgroup$







  • 1




    $begingroup$
    Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
    $endgroup$
    – Yuval Filmus
    2 hours ago













2












2








2





$begingroup$


Was doing a little interview prep. Given an undirected graph G, such that each node is colored red or blue and |E|≥|V|, find a path in O(|E|) time such that starting and ending at 2 blue nodes, s and t, that you pass through as few red nodes as possible.



Initial Impressions: Since |E|≥|V|, O(|E|) time would include O(|E|+|V|), which means the solution likely uses BFS or DFS. Modifying the graph such that causing the all red nodes must be forced down a directed path of some long length (after making the whole graph directed) in order to use out-of-the-box BFS seems not viable, as it would mean constructing a new graph would be along O(|E||V|) time.



Another method I toyed around with was propagating values to nodes based on the safest path to that node while doing a DFS search, but not all values were guaranteed to update.



I still want to try to solve this myself, but I'm really stuck right now. Was wondering if there were any hints I could get. There are much simpler ways of doing this if it weren't for the O(|E|) time. Djikstras with creating some edge weights would work, but wouldn't be within the time bound.










share|cite|improve this question









$endgroup$




Was doing a little interview prep. Given an undirected graph G, such that each node is colored red or blue and |E|≥|V|, find a path in O(|E|) time such that starting and ending at 2 blue nodes, s and t, that you pass through as few red nodes as possible.



Initial Impressions: Since |E|≥|V|, O(|E|) time would include O(|E|+|V|), which means the solution likely uses BFS or DFS. Modifying the graph such that causing the all red nodes must be forced down a directed path of some long length (after making the whole graph directed) in order to use out-of-the-box BFS seems not viable, as it would mean constructing a new graph would be along O(|E||V|) time.



Another method I toyed around with was propagating values to nodes based on the safest path to that node while doing a DFS search, but not all values were guaranteed to update.



I still want to try to solve this myself, but I'm really stuck right now. Was wondering if there were any hints I could get. There are much simpler ways of doing this if it weren't for the O(|E|) time. Djikstras with creating some edge weights would work, but wouldn't be within the time bound.







graphs






share|cite|improve this question













share|cite|improve this question











share|cite|improve this question




share|cite|improve this question










asked 5 hours ago









Hunter DyerHunter Dyer

284




284







  • 1




    $begingroup$
    Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
    $endgroup$
    – Yuval Filmus
    2 hours ago












  • 1




    $begingroup$
    Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
    $endgroup$
    – Yuval Filmus
    2 hours ago







1




1




$begingroup$
Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
$endgroup$
– Yuval Filmus
2 hours ago




$begingroup$
Try a variant of BFS in which you first find all red nodes reachable only via blue nodes, and so on.
$endgroup$
– Yuval Filmus
2 hours ago










2 Answers
2






active

oldest

votes


















2












$begingroup$

To solve this, you need to use $BFS$. But first, manipulate $G$ so that the path will always favor blue vertices.



The solution has 2 parts:



  1. Use $DFS$ on blue vertices only, to find all all-blue strongly connected components, or $SCC$. Let's denote each $SCC$ by $v'$. Now, each blue $v in v'$ will be "compressed" to a single vertex $u$, and an edge $(u,x)$ will be added for every $x in N(v')$.
    Note any such $x$ is necessarily red.
    This step costs $O(V+E) = O(E)$, since $DFS$ is $O(V+E)$, and you have at most $V$ blue vertices, which make no more than $E$ new edges to add.

Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertice.



  1. Use $BFS$ from $s$. That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.





share|cite|improve this answer









$endgroup$




















    1












    $begingroup$

    Convert $G$ to a directed graph $G'$ where we have two edges $(u,v)$ and $(v,u)$ in $G'$ for every edge $u,v$ in $G$. Let the length of $(u,v)$ be 1 if $v$ is a red node and 0 otherwise. Now run Dijkstra's algorithm on $G'$ from the starting node $s$ to the ending node $t$.



    It is clear that the shortest path thus found passes as few red nodes as possible.






    share|cite|improve this answer









    $endgroup$












    • $begingroup$
      Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
      $endgroup$
      – Hunter Dyer
      22 mins ago










    • $begingroup$
      I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
      $endgroup$
      – Apass.Jack
      8 mins ago












    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "419"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcs.stackexchange.com%2fquestions%2f106337%2ffind-a-path-from-s-to-t-using-as-few-red-nodes-as-possible%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    To solve this, you need to use $BFS$. But first, manipulate $G$ so that the path will always favor blue vertices.



    The solution has 2 parts:



    1. Use $DFS$ on blue vertices only, to find all all-blue strongly connected components, or $SCC$. Let's denote each $SCC$ by $v'$. Now, each blue $v in v'$ will be "compressed" to a single vertex $u$, and an edge $(u,x)$ will be added for every $x in N(v')$.
      Note any such $x$ is necessarily red.
      This step costs $O(V+E) = O(E)$, since $DFS$ is $O(V+E)$, and you have at most $V$ blue vertices, which make no more than $E$ new edges to add.

    Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertice.



    1. Use $BFS$ from $s$. That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.





    share|cite|improve this answer









    $endgroup$

















      2












      $begingroup$

      To solve this, you need to use $BFS$. But first, manipulate $G$ so that the path will always favor blue vertices.



      The solution has 2 parts:



      1. Use $DFS$ on blue vertices only, to find all all-blue strongly connected components, or $SCC$. Let's denote each $SCC$ by $v'$. Now, each blue $v in v'$ will be "compressed" to a single vertex $u$, and an edge $(u,x)$ will be added for every $x in N(v')$.
        Note any such $x$ is necessarily red.
        This step costs $O(V+E) = O(E)$, since $DFS$ is $O(V+E)$, and you have at most $V$ blue vertices, which make no more than $E$ new edges to add.

      Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertice.



      1. Use $BFS$ from $s$. That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.





      share|cite|improve this answer









      $endgroup$















        2












        2








        2





        $begingroup$

        To solve this, you need to use $BFS$. But first, manipulate $G$ so that the path will always favor blue vertices.



        The solution has 2 parts:



        1. Use $DFS$ on blue vertices only, to find all all-blue strongly connected components, or $SCC$. Let's denote each $SCC$ by $v'$. Now, each blue $v in v'$ will be "compressed" to a single vertex $u$, and an edge $(u,x)$ will be added for every $x in N(v')$.
          Note any such $x$ is necessarily red.
          This step costs $O(V+E) = O(E)$, since $DFS$ is $O(V+E)$, and you have at most $V$ blue vertices, which make no more than $E$ new edges to add.

        Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertice.



        1. Use $BFS$ from $s$. That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.





        share|cite|improve this answer









        $endgroup$



        To solve this, you need to use $BFS$. But first, manipulate $G$ so that the path will always favor blue vertices.



        The solution has 2 parts:



        1. Use $DFS$ on blue vertices only, to find all all-blue strongly connected components, or $SCC$. Let's denote each $SCC$ by $v'$. Now, each blue $v in v'$ will be "compressed" to a single vertex $u$, and an edge $(u,x)$ will be added for every $x in N(v')$.
          Note any such $x$ is necessarily red.
          This step costs $O(V+E) = O(E)$, since $DFS$ is $O(V+E)$, and you have at most $V$ blue vertices, which make no more than $E$ new edges to add.

        Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertice.



        1. Use $BFS$ from $s$. That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.






        share|cite|improve this answer












        share|cite|improve this answer



        share|cite|improve this answer










        answered 1 hour ago









        loxlox

        1666




        1666





















            1












            $begingroup$

            Convert $G$ to a directed graph $G'$ where we have two edges $(u,v)$ and $(v,u)$ in $G'$ for every edge $u,v$ in $G$. Let the length of $(u,v)$ be 1 if $v$ is a red node and 0 otherwise. Now run Dijkstra's algorithm on $G'$ from the starting node $s$ to the ending node $t$.



            It is clear that the shortest path thus found passes as few red nodes as possible.






            share|cite|improve this answer









            $endgroup$












            • $begingroup$
              Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
              $endgroup$
              – Hunter Dyer
              22 mins ago










            • $begingroup$
              I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
              $endgroup$
              – Apass.Jack
              8 mins ago
















            1












            $begingroup$

            Convert $G$ to a directed graph $G'$ where we have two edges $(u,v)$ and $(v,u)$ in $G'$ for every edge $u,v$ in $G$. Let the length of $(u,v)$ be 1 if $v$ is a red node and 0 otherwise. Now run Dijkstra's algorithm on $G'$ from the starting node $s$ to the ending node $t$.



            It is clear that the shortest path thus found passes as few red nodes as possible.






            share|cite|improve this answer









            $endgroup$












            • $begingroup$
              Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
              $endgroup$
              – Hunter Dyer
              22 mins ago










            • $begingroup$
              I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
              $endgroup$
              – Apass.Jack
              8 mins ago














            1












            1








            1





            $begingroup$

            Convert $G$ to a directed graph $G'$ where we have two edges $(u,v)$ and $(v,u)$ in $G'$ for every edge $u,v$ in $G$. Let the length of $(u,v)$ be 1 if $v$ is a red node and 0 otherwise. Now run Dijkstra's algorithm on $G'$ from the starting node $s$ to the ending node $t$.



            It is clear that the shortest path thus found passes as few red nodes as possible.






            share|cite|improve this answer









            $endgroup$



            Convert $G$ to a directed graph $G'$ where we have two edges $(u,v)$ and $(v,u)$ in $G'$ for every edge $u,v$ in $G$. Let the length of $(u,v)$ be 1 if $v$ is a red node and 0 otherwise. Now run Dijkstra's algorithm on $G'$ from the starting node $s$ to the ending node $t$.



            It is clear that the shortest path thus found passes as few red nodes as possible.







            share|cite|improve this answer












            share|cite|improve this answer



            share|cite|improve this answer










            answered 35 mins ago









            Apass.JackApass.Jack

            13.7k1940




            13.7k1940











            • $begingroup$
              Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
              $endgroup$
              – Hunter Dyer
              22 mins ago










            • $begingroup$
              I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
              $endgroup$
              – Apass.Jack
              8 mins ago

















            • $begingroup$
              Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
              $endgroup$
              – Hunter Dyer
              22 mins ago










            • $begingroup$
              I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
              $endgroup$
              – Apass.Jack
              8 mins ago
















            $begingroup$
            Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
            $endgroup$
            – Hunter Dyer
            22 mins ago




            $begingroup$
            Yeah that definitely works, but the runtime of Dijkstra's is O(|E| + |V|log|V|) which is more than O(|E|).
            $endgroup$
            – Hunter Dyer
            22 mins ago












            $begingroup$
            I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
            $endgroup$
            – Apass.Jack
            8 mins ago





            $begingroup$
            I will show shortly that this particular run of Dijkstra's algorithm actually takes $O(|E|)$ time.
            $endgroup$
            – Apass.Jack
            8 mins ago


















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Computer Science Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcs.stackexchange.com%2fquestions%2f106337%2ffind-a-path-from-s-to-t-using-as-few-red-nodes-as-possible%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar

            香港授勳及嘉獎制度 目录 勳章及獎狀類別 嘉獎等級 授勳及嘉獎提名 統計數字 多次獲頒勳章或獎狀的人士 爭議 褫奪機制 参考文献 外部連結 参见 导航菜单統計數字一九九七年七月二日(星期三)香港特別行政區的授勳制度六七暴動領袖獲大紫荊勳章 董建華被斥為肯定殺人放火董建華授勳楊光 議員窮追猛打蘋論:顛倒是非黑白的大紫荊董讚楊光有貢獻避談暴動董拒答授勳楊光原因撤除勳銜撤除勳銜撤除勳銜特首掌「搣柴」生殺權行為失當罪 隨時「搣柴」失長糧政府刊憲 許仕仁郭炳江遭「搣柴」去年中終極上訴失敗 許仕仁郭炳江撤勳章太平紳士猛料阿Sir講古—— 「搣柴」有故一九九八年授勳名單一九九九年授勳名單二○○三年授勳名單二○○八年授勳名單二○○七年授勳名單政府總部禮賓處 - 授勳及嘉獎香港特別行政區勳章綬帶一覽(PDF)(非官方)