Finding paths in a Undirected Graph












9














Consider the following graph:



dummy graph



Represented by the following array structure:



$graph = array
(
'a' => array(),
'b' => array('a'),
'c' => array('a', 'b'),
'd' => array('a'),
'e' => array('d'),
'f' => array('a', 'b', 'c', 'd'),
'g' => array('d'),
'h' => array('c'),
'i' => array('c', 'g'),
'j' => array(),
);


What is the most efficient algorithm to find all paths (not just the shortest one) from node X to node Y in either direction without repeating nodes? For instance, the paths that lead from node C to node A are:



C --> A
C --> B --> A
C --> F --> A
C --> F --> B --> A
C --> F --> D --> A
C --> I --> G --> D --> A


Finding all the paths using the parent nodes of node X (A and B, in the example for node C) is trivial, but I am having a really hard time traversing the nodes in a descendant / hybrid direction.



Can someone help me out?





UPDATE: Following @JackManey advice, I tried to port IDDFS (Iterative Deepening Depth-First Search) based on the Wikipedia pseudo-code and this is more or less what my code looks like:



$graph = directed2Undirected($graph);

function IDDFS($root, $goal) {
$depth = 0;

while ($depth <= 2) { // 2 is hard-coded for now
$result = DLS($root, $goal, $depth);

if ($result !== false) {
return $result;
}

$depth++;
}
}

function DLS($node, $goal, $depth) {
global $graph;

if (($depth >= 0) && ($node == $goal)) {
return $node;
}

else if ($depth > 0) {
foreach (expand($node, $graph) as $child) {
return DLS($child, $goal, $depth - 1);
}
}

else {
return false;
}
}


And here are the helper functions used by it:



function directed2Undirected($data) {
foreach ($data as $key => $values) {
foreach ($values as $value) {
$data[$value] = $key;
}
}

return $data;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

return array_unique(flatten(array_intersect_key($data, array_flip((array) $id))));
}

function flatten($data) {
$result = array();

if (is_array($data) === true) {
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $value) {
$result = $value;
}
}

return $result;
}


Calling the above yields weird or incomplete results:



var_dump(IDDFS('c', 'a')); // a -- only 1 path?
var_dump(IDDFS('c', 'd')); // NULL -- can't find this path?!


I think I'm overlooking something from the pseudo-code, but I'm not sure what it is.





I also tried this DFS class that was recommended in another question, although it seems to always find one path from node X to node Y, I can't get it to return all paths (demo for C -> A and C -> D).





Since I don't need to know the path actually taken, only how many paths exist that require n number of steps to get from node X to node Y, I came up with this function (uses directed2Undirected above):



$graph = directed2Undirected($graph);

function Distance($node, $graph, $depth = 0) {
$result = array();

if (array_key_exists($node, $graph) === true) {
$result = array_fill_keys(array_keys($graph), 0);

foreach (expand($node, $graph, $depth - 1) as $child) {
if (strcmp($node, $child) !== 0) {
$result[$child] += $depth;
}
}

$result[$node] = -1;
}

return $result;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

// no array_unique() now!
return flatten(array_intersect_key($data, array_flip((array) $id)));
}


For Distance('c', $graph, 0), Distance('c', $graph, 1) and Distance('c', $graph, 2) this correctly returns the sum of the distance between C and any other node. The problem is, with Distance('c', $graph, 3) (and higher) it start repeating nodes and returning wrong results:



Array
(
[a] => 12
[b] => 9
[c] => -1
[d] => 9
[e] => 3
[f] => 12
[g] => 3
[h] => 3
[i] => 6
[j] => 0
)


The index a should only be 6 (3 + 3), since the only ways I can get from C to A using 3 steps are:



C --> F --> B --> A
C --> F --> D --> A


Yet, it seems to be considering two (only?) additional paths that repeat nodes:



C --> A --> C --> A
C --> B --> C --> A
C --> F --> C --> A
C --> H --> C --> A
C --> I --> C --> A


Of course, index a isn't the only wrong one. The problem seems to be expand() but I'm not sure how to fix it, array_diff(expand('c', $graph, $i), expand('c', $graph, $i - 2)) seems to fix this particular error, but that ain't a proper fix... Help?





dummy graph againagain, so you don't have to scroll










share|improve this question




















  • 2




    Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
    – danielrsmith
    May 29 '12 at 17:52










  • @danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
    – Alix Axel
    May 29 '12 at 17:58










  • Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
    – goat
    May 30 '12 at 4:08












  • @chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
    – Alix Axel
    May 30 '12 at 4:24
















9














Consider the following graph:



dummy graph



Represented by the following array structure:



$graph = array
(
'a' => array(),
'b' => array('a'),
'c' => array('a', 'b'),
'd' => array('a'),
'e' => array('d'),
'f' => array('a', 'b', 'c', 'd'),
'g' => array('d'),
'h' => array('c'),
'i' => array('c', 'g'),
'j' => array(),
);


What is the most efficient algorithm to find all paths (not just the shortest one) from node X to node Y in either direction without repeating nodes? For instance, the paths that lead from node C to node A are:



C --> A
C --> B --> A
C --> F --> A
C --> F --> B --> A
C --> F --> D --> A
C --> I --> G --> D --> A


Finding all the paths using the parent nodes of node X (A and B, in the example for node C) is trivial, but I am having a really hard time traversing the nodes in a descendant / hybrid direction.



Can someone help me out?





UPDATE: Following @JackManey advice, I tried to port IDDFS (Iterative Deepening Depth-First Search) based on the Wikipedia pseudo-code and this is more or less what my code looks like:



$graph = directed2Undirected($graph);

function IDDFS($root, $goal) {
$depth = 0;

while ($depth <= 2) { // 2 is hard-coded for now
$result = DLS($root, $goal, $depth);

if ($result !== false) {
return $result;
}

$depth++;
}
}

function DLS($node, $goal, $depth) {
global $graph;

if (($depth >= 0) && ($node == $goal)) {
return $node;
}

else if ($depth > 0) {
foreach (expand($node, $graph) as $child) {
return DLS($child, $goal, $depth - 1);
}
}

else {
return false;
}
}


And here are the helper functions used by it:



function directed2Undirected($data) {
foreach ($data as $key => $values) {
foreach ($values as $value) {
$data[$value] = $key;
}
}

return $data;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

return array_unique(flatten(array_intersect_key($data, array_flip((array) $id))));
}

function flatten($data) {
$result = array();

if (is_array($data) === true) {
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $value) {
$result = $value;
}
}

return $result;
}


Calling the above yields weird or incomplete results:



var_dump(IDDFS('c', 'a')); // a -- only 1 path?
var_dump(IDDFS('c', 'd')); // NULL -- can't find this path?!


I think I'm overlooking something from the pseudo-code, but I'm not sure what it is.





I also tried this DFS class that was recommended in another question, although it seems to always find one path from node X to node Y, I can't get it to return all paths (demo for C -> A and C -> D).





Since I don't need to know the path actually taken, only how many paths exist that require n number of steps to get from node X to node Y, I came up with this function (uses directed2Undirected above):



$graph = directed2Undirected($graph);

function Distance($node, $graph, $depth = 0) {
$result = array();

if (array_key_exists($node, $graph) === true) {
$result = array_fill_keys(array_keys($graph), 0);

foreach (expand($node, $graph, $depth - 1) as $child) {
if (strcmp($node, $child) !== 0) {
$result[$child] += $depth;
}
}

$result[$node] = -1;
}

return $result;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

// no array_unique() now!
return flatten(array_intersect_key($data, array_flip((array) $id)));
}


For Distance('c', $graph, 0), Distance('c', $graph, 1) and Distance('c', $graph, 2) this correctly returns the sum of the distance between C and any other node. The problem is, with Distance('c', $graph, 3) (and higher) it start repeating nodes and returning wrong results:



Array
(
[a] => 12
[b] => 9
[c] => -1
[d] => 9
[e] => 3
[f] => 12
[g] => 3
[h] => 3
[i] => 6
[j] => 0
)


The index a should only be 6 (3 + 3), since the only ways I can get from C to A using 3 steps are:



C --> F --> B --> A
C --> F --> D --> A


Yet, it seems to be considering two (only?) additional paths that repeat nodes:



C --> A --> C --> A
C --> B --> C --> A
C --> F --> C --> A
C --> H --> C --> A
C --> I --> C --> A


Of course, index a isn't the only wrong one. The problem seems to be expand() but I'm not sure how to fix it, array_diff(expand('c', $graph, $i), expand('c', $graph, $i - 2)) seems to fix this particular error, but that ain't a proper fix... Help?





dummy graph againagain, so you don't have to scroll










share|improve this question




















  • 2




    Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
    – danielrsmith
    May 29 '12 at 17:52










  • @danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
    – Alix Axel
    May 29 '12 at 17:58










  • Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
    – goat
    May 30 '12 at 4:08












  • @chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
    – Alix Axel
    May 30 '12 at 4:24














9












9








9


1





Consider the following graph:



dummy graph



Represented by the following array structure:



$graph = array
(
'a' => array(),
'b' => array('a'),
'c' => array('a', 'b'),
'd' => array('a'),
'e' => array('d'),
'f' => array('a', 'b', 'c', 'd'),
'g' => array('d'),
'h' => array('c'),
'i' => array('c', 'g'),
'j' => array(),
);


What is the most efficient algorithm to find all paths (not just the shortest one) from node X to node Y in either direction without repeating nodes? For instance, the paths that lead from node C to node A are:



C --> A
C --> B --> A
C --> F --> A
C --> F --> B --> A
C --> F --> D --> A
C --> I --> G --> D --> A


Finding all the paths using the parent nodes of node X (A and B, in the example for node C) is trivial, but I am having a really hard time traversing the nodes in a descendant / hybrid direction.



Can someone help me out?





UPDATE: Following @JackManey advice, I tried to port IDDFS (Iterative Deepening Depth-First Search) based on the Wikipedia pseudo-code and this is more or less what my code looks like:



$graph = directed2Undirected($graph);

function IDDFS($root, $goal) {
$depth = 0;

while ($depth <= 2) { // 2 is hard-coded for now
$result = DLS($root, $goal, $depth);

if ($result !== false) {
return $result;
}

$depth++;
}
}

function DLS($node, $goal, $depth) {
global $graph;

if (($depth >= 0) && ($node == $goal)) {
return $node;
}

else if ($depth > 0) {
foreach (expand($node, $graph) as $child) {
return DLS($child, $goal, $depth - 1);
}
}

else {
return false;
}
}


And here are the helper functions used by it:



function directed2Undirected($data) {
foreach ($data as $key => $values) {
foreach ($values as $value) {
$data[$value] = $key;
}
}

return $data;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

return array_unique(flatten(array_intersect_key($data, array_flip((array) $id))));
}

function flatten($data) {
$result = array();

if (is_array($data) === true) {
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $value) {
$result = $value;
}
}

return $result;
}


Calling the above yields weird or incomplete results:



var_dump(IDDFS('c', 'a')); // a -- only 1 path?
var_dump(IDDFS('c', 'd')); // NULL -- can't find this path?!


I think I'm overlooking something from the pseudo-code, but I'm not sure what it is.





I also tried this DFS class that was recommended in another question, although it seems to always find one path from node X to node Y, I can't get it to return all paths (demo for C -> A and C -> D).





Since I don't need to know the path actually taken, only how many paths exist that require n number of steps to get from node X to node Y, I came up with this function (uses directed2Undirected above):



$graph = directed2Undirected($graph);

function Distance($node, $graph, $depth = 0) {
$result = array();

if (array_key_exists($node, $graph) === true) {
$result = array_fill_keys(array_keys($graph), 0);

foreach (expand($node, $graph, $depth - 1) as $child) {
if (strcmp($node, $child) !== 0) {
$result[$child] += $depth;
}
}

$result[$node] = -1;
}

return $result;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

// no array_unique() now!
return flatten(array_intersect_key($data, array_flip((array) $id)));
}


For Distance('c', $graph, 0), Distance('c', $graph, 1) and Distance('c', $graph, 2) this correctly returns the sum of the distance between C and any other node. The problem is, with Distance('c', $graph, 3) (and higher) it start repeating nodes and returning wrong results:



Array
(
[a] => 12
[b] => 9
[c] => -1
[d] => 9
[e] => 3
[f] => 12
[g] => 3
[h] => 3
[i] => 6
[j] => 0
)


The index a should only be 6 (3 + 3), since the only ways I can get from C to A using 3 steps are:



C --> F --> B --> A
C --> F --> D --> A


Yet, it seems to be considering two (only?) additional paths that repeat nodes:



C --> A --> C --> A
C --> B --> C --> A
C --> F --> C --> A
C --> H --> C --> A
C --> I --> C --> A


Of course, index a isn't the only wrong one. The problem seems to be expand() but I'm not sure how to fix it, array_diff(expand('c', $graph, $i), expand('c', $graph, $i - 2)) seems to fix this particular error, but that ain't a proper fix... Help?





dummy graph againagain, so you don't have to scroll










share|improve this question















Consider the following graph:



dummy graph



Represented by the following array structure:



$graph = array
(
'a' => array(),
'b' => array('a'),
'c' => array('a', 'b'),
'd' => array('a'),
'e' => array('d'),
'f' => array('a', 'b', 'c', 'd'),
'g' => array('d'),
'h' => array('c'),
'i' => array('c', 'g'),
'j' => array(),
);


What is the most efficient algorithm to find all paths (not just the shortest one) from node X to node Y in either direction without repeating nodes? For instance, the paths that lead from node C to node A are:



C --> A
C --> B --> A
C --> F --> A
C --> F --> B --> A
C --> F --> D --> A
C --> I --> G --> D --> A


Finding all the paths using the parent nodes of node X (A and B, in the example for node C) is trivial, but I am having a really hard time traversing the nodes in a descendant / hybrid direction.



Can someone help me out?





UPDATE: Following @JackManey advice, I tried to port IDDFS (Iterative Deepening Depth-First Search) based on the Wikipedia pseudo-code and this is more or less what my code looks like:



$graph = directed2Undirected($graph);

function IDDFS($root, $goal) {
$depth = 0;

while ($depth <= 2) { // 2 is hard-coded for now
$result = DLS($root, $goal, $depth);

if ($result !== false) {
return $result;
}

$depth++;
}
}

function DLS($node, $goal, $depth) {
global $graph;

if (($depth >= 0) && ($node == $goal)) {
return $node;
}

else if ($depth > 0) {
foreach (expand($node, $graph) as $child) {
return DLS($child, $goal, $depth - 1);
}
}

else {
return false;
}
}


And here are the helper functions used by it:



function directed2Undirected($data) {
foreach ($data as $key => $values) {
foreach ($values as $value) {
$data[$value] = $key;
}
}

return $data;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

return array_unique(flatten(array_intersect_key($data, array_flip((array) $id))));
}

function flatten($data) {
$result = array();

if (is_array($data) === true) {
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $value) {
$result = $value;
}
}

return $result;
}


Calling the above yields weird or incomplete results:



var_dump(IDDFS('c', 'a')); // a -- only 1 path?
var_dump(IDDFS('c', 'd')); // NULL -- can't find this path?!


I think I'm overlooking something from the pseudo-code, but I'm not sure what it is.





I also tried this DFS class that was recommended in another question, although it seems to always find one path from node X to node Y, I can't get it to return all paths (demo for C -> A and C -> D).





Since I don't need to know the path actually taken, only how many paths exist that require n number of steps to get from node X to node Y, I came up with this function (uses directed2Undirected above):



$graph = directed2Undirected($graph);

function Distance($node, $graph, $depth = 0) {
$result = array();

if (array_key_exists($node, $graph) === true) {
$result = array_fill_keys(array_keys($graph), 0);

foreach (expand($node, $graph, $depth - 1) as $child) {
if (strcmp($node, $child) !== 0) {
$result[$child] += $depth;
}
}

$result[$node] = -1;
}

return $result;
}

function expand($id, $data, $depth = 0) {
while (--$depth >= 0) {
$id = flatten(array_intersect_key($data, array_flip((array) $id)));
}

// no array_unique() now!
return flatten(array_intersect_key($data, array_flip((array) $id)));
}


For Distance('c', $graph, 0), Distance('c', $graph, 1) and Distance('c', $graph, 2) this correctly returns the sum of the distance between C and any other node. The problem is, with Distance('c', $graph, 3) (and higher) it start repeating nodes and returning wrong results:



Array
(
[a] => 12
[b] => 9
[c] => -1
[d] => 9
[e] => 3
[f] => 12
[g] => 3
[h] => 3
[i] => 6
[j] => 0
)


The index a should only be 6 (3 + 3), since the only ways I can get from C to A using 3 steps are:



C --> F --> B --> A
C --> F --> D --> A


Yet, it seems to be considering two (only?) additional paths that repeat nodes:



C --> A --> C --> A
C --> B --> C --> A
C --> F --> C --> A
C --> H --> C --> A
C --> I --> C --> A


Of course, index a isn't the only wrong one. The problem seems to be expand() but I'm not sure how to fix it, array_diff(expand('c', $graph, $i), expand('c', $graph, $i - 2)) seems to fix this particular error, but that ain't a proper fix... Help?





dummy graph againagain, so you don't have to scroll







php algorithm graph graph-algorithm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 30 '12 at 17:47







Alix Axel

















asked May 29 '12 at 17:48









Alix AxelAlix Axel

106k70340458




106k70340458








  • 2




    Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
    – danielrsmith
    May 29 '12 at 17:52










  • @danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
    – Alix Axel
    May 29 '12 at 17:58










  • Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
    – goat
    May 30 '12 at 4:08












  • @chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
    – Alix Axel
    May 30 '12 at 4:24














  • 2




    Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
    – danielrsmith
    May 29 '12 at 17:52










  • @danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
    – Alix Axel
    May 29 '12 at 17:58










  • Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
    – goat
    May 30 '12 at 4:08












  • @chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
    – Alix Axel
    May 30 '12 at 4:24








2




2




Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
– danielrsmith
May 29 '12 at 17:52




Your picture and array show a "directed" graph. Did you perhaps mean an "unweighted" graph?
– danielrsmith
May 29 '12 at 17:52












@danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
– Alix Axel
May 29 '12 at 17:58




@danielrsmith: Sorry about that, I meant to add arrows in both directions but forgot to do that. To clarify, the graph is undirected and unweighted. =)
– Alix Axel
May 29 '12 at 17:58












Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
– goat
May 30 '12 at 4:08






Do you really want all paths between two nodes? That can be a pretty large number of paths even with your restriction that a path can contain any given node a max of one time. For example, if the graph was complete(an edge between any two vertices), and had 10 vertices, if im not mistaken there would be 9! paths between any two nodes.
– goat
May 30 '12 at 4:08














@chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
– Alix Axel
May 30 '12 at 4:24




@chris: In principle, yes -- but I'll be limiting the distance from the origin node to a maximum of 3 steps or so (depending on how fast it will perform).
– Alix Axel
May 30 '12 at 4:24












2 Answers
2






active

oldest

votes


















2














In general, you can do a depth-first search or a breadth-first search, although neither one is superior to the other (since it's easy to come up with examples for which one is superior to the other).



Edit: Upon rereading the question and thinking a bit, since you want all paths from C to A, a DFS starting at C would probably make the most sense. Along the way, you'd have to store sequences of edges and throw sequences away if they don't end up at A.






share|improve this answer























  • I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
    – Alix Axel
    May 29 '12 at 18:04










  • I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
    – Alix Axel
    May 29 '12 at 18:05












  • @AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
    – user554546
    May 29 '12 at 18:16










  • I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
    – Alix Axel
    May 30 '12 at 17:51



















0














$stdin = fopen('php://stdin','r');
$stdin = fopen('php://stdin','w');



fscanf(STDIN,"%dn",$n);
fscanf(STDIN,"%dn",$e);
$graph = array();


for ($i = 0;$i<$n; $i++)
{
$graph[$i] = array();
}


for ($i = 0;$i<$e; $i++)
{
fscanf(STDIN,"%s%s",$x,$y);
$row = ord($x[0]) - ord('A');
$row = ord($y[0]) - ord('A');
echo $row." ".$col;

$graph[$row][$col] = 1;
$graph[$col][$row] = 1;
}

for ($i = 0;$i <$n; $i++)
{
for ($j= 0;$j<$n ;$j++)
{
if ($graph[$i][$j]==1)
{
echo"1 ";
}
else{
echo"0 ";
}
echo "n";
}
}





share|improve this answer





















  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Dang Nguyen
    Dec 28 '18 at 5:35










  • Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
    – aliusman
    Dec 28 '18 at 5:35











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
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: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
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%2fstackoverflow.com%2fquestions%2f10804148%2ffinding-paths-in-a-undirected-graph%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














In general, you can do a depth-first search or a breadth-first search, although neither one is superior to the other (since it's easy to come up with examples for which one is superior to the other).



Edit: Upon rereading the question and thinking a bit, since you want all paths from C to A, a DFS starting at C would probably make the most sense. Along the way, you'd have to store sequences of edges and throw sequences away if they don't end up at A.






share|improve this answer























  • I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
    – Alix Axel
    May 29 '12 at 18:04










  • I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
    – Alix Axel
    May 29 '12 at 18:05












  • @AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
    – user554546
    May 29 '12 at 18:16










  • I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
    – Alix Axel
    May 30 '12 at 17:51
















2














In general, you can do a depth-first search or a breadth-first search, although neither one is superior to the other (since it's easy to come up with examples for which one is superior to the other).



Edit: Upon rereading the question and thinking a bit, since you want all paths from C to A, a DFS starting at C would probably make the most sense. Along the way, you'd have to store sequences of edges and throw sequences away if they don't end up at A.






share|improve this answer























  • I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
    – Alix Axel
    May 29 '12 at 18:04










  • I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
    – Alix Axel
    May 29 '12 at 18:05












  • @AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
    – user554546
    May 29 '12 at 18:16










  • I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
    – Alix Axel
    May 30 '12 at 17:51














2












2








2






In general, you can do a depth-first search or a breadth-first search, although neither one is superior to the other (since it's easy to come up with examples for which one is superior to the other).



Edit: Upon rereading the question and thinking a bit, since you want all paths from C to A, a DFS starting at C would probably make the most sense. Along the way, you'd have to store sequences of edges and throw sequences away if they don't end up at A.






share|improve this answer














In general, you can do a depth-first search or a breadth-first search, although neither one is superior to the other (since it's easy to come up with examples for which one is superior to the other).



Edit: Upon rereading the question and thinking a bit, since you want all paths from C to A, a DFS starting at C would probably make the most sense. Along the way, you'd have to store sequences of edges and throw sequences away if they don't end up at A.







share|improve this answer














share|improve this answer



share|improve this answer








edited May 29 '12 at 18:16

























answered May 29 '12 at 17:53







user554546



















  • I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
    – Alix Axel
    May 29 '12 at 18:04










  • I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
    – Alix Axel
    May 29 '12 at 18:05












  • @AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
    – user554546
    May 29 '12 at 18:16










  • I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
    – Alix Axel
    May 30 '12 at 17:51


















  • I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
    – Alix Axel
    May 29 '12 at 18:04










  • I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
    – Alix Axel
    May 29 '12 at 18:05












  • @AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
    – user554546
    May 29 '12 at 18:16










  • I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
    – Alix Axel
    May 30 '12 at 17:51
















I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
– Alix Axel
May 29 '12 at 18:04




I've read about the two, from my understanding DFS has more problems with repeating nodes / infinite loops. I tried implementing BFS using the Wikipedia pseudo-code but I couldn't generate the results I was looking for, perhaps I've missed something. I've also searched on literateprograms.org and algorithmist.com/index.php/Breadth-First_Search for concrete implementations, but the description is a bit vague.
– Alix Axel
May 29 '12 at 18:04












I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
– Alix Axel
May 29 '12 at 18:05






I've since lost my BFS implementation, but I'll have my go at it again and I'll post the results here. Meanwhile, if you know of any resources that would allow me to comprehend BFS better, please do tell. =)
– Alix Axel
May 29 '12 at 18:05














@AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
– user554546
May 29 '12 at 18:16




@AlixAxel - Actually, upon some reflection, a depth-first search is probably what you need. Take a look at the edit above.
– user554546
May 29 '12 at 18:16












I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
– Alix Axel
May 30 '12 at 17:51




I tried a bunch of stuff and I still didn't manage to crack this, do you mind having a look at my update?
– Alix Axel
May 30 '12 at 17:51













0














$stdin = fopen('php://stdin','r');
$stdin = fopen('php://stdin','w');



fscanf(STDIN,"%dn",$n);
fscanf(STDIN,"%dn",$e);
$graph = array();


for ($i = 0;$i<$n; $i++)
{
$graph[$i] = array();
}


for ($i = 0;$i<$e; $i++)
{
fscanf(STDIN,"%s%s",$x,$y);
$row = ord($x[0]) - ord('A');
$row = ord($y[0]) - ord('A');
echo $row." ".$col;

$graph[$row][$col] = 1;
$graph[$col][$row] = 1;
}

for ($i = 0;$i <$n; $i++)
{
for ($j= 0;$j<$n ;$j++)
{
if ($graph[$i][$j]==1)
{
echo"1 ";
}
else{
echo"0 ";
}
echo "n";
}
}





share|improve this answer





















  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Dang Nguyen
    Dec 28 '18 at 5:35










  • Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
    – aliusman
    Dec 28 '18 at 5:35
















0














$stdin = fopen('php://stdin','r');
$stdin = fopen('php://stdin','w');



fscanf(STDIN,"%dn",$n);
fscanf(STDIN,"%dn",$e);
$graph = array();


for ($i = 0;$i<$n; $i++)
{
$graph[$i] = array();
}


for ($i = 0;$i<$e; $i++)
{
fscanf(STDIN,"%s%s",$x,$y);
$row = ord($x[0]) - ord('A');
$row = ord($y[0]) - ord('A');
echo $row." ".$col;

$graph[$row][$col] = 1;
$graph[$col][$row] = 1;
}

for ($i = 0;$i <$n; $i++)
{
for ($j= 0;$j<$n ;$j++)
{
if ($graph[$i][$j]==1)
{
echo"1 ";
}
else{
echo"0 ";
}
echo "n";
}
}





share|improve this answer





















  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Dang Nguyen
    Dec 28 '18 at 5:35










  • Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
    – aliusman
    Dec 28 '18 at 5:35














0












0








0






$stdin = fopen('php://stdin','r');
$stdin = fopen('php://stdin','w');



fscanf(STDIN,"%dn",$n);
fscanf(STDIN,"%dn",$e);
$graph = array();


for ($i = 0;$i<$n; $i++)
{
$graph[$i] = array();
}


for ($i = 0;$i<$e; $i++)
{
fscanf(STDIN,"%s%s",$x,$y);
$row = ord($x[0]) - ord('A');
$row = ord($y[0]) - ord('A');
echo $row." ".$col;

$graph[$row][$col] = 1;
$graph[$col][$row] = 1;
}

for ($i = 0;$i <$n; $i++)
{
for ($j= 0;$j<$n ;$j++)
{
if ($graph[$i][$j]==1)
{
echo"1 ";
}
else{
echo"0 ";
}
echo "n";
}
}





share|improve this answer












$stdin = fopen('php://stdin','r');
$stdin = fopen('php://stdin','w');



fscanf(STDIN,"%dn",$n);
fscanf(STDIN,"%dn",$e);
$graph = array();


for ($i = 0;$i<$n; $i++)
{
$graph[$i] = array();
}


for ($i = 0;$i<$e; $i++)
{
fscanf(STDIN,"%s%s",$x,$y);
$row = ord($x[0]) - ord('A');
$row = ord($y[0]) - ord('A');
echo $row." ".$col;

$graph[$row][$col] = 1;
$graph[$col][$row] = 1;
}

for ($i = 0;$i <$n; $i++)
{
for ($j= 0;$j<$n ;$j++)
{
if ($graph[$i][$j]==1)
{
echo"1 ";
}
else{
echo"0 ";
}
echo "n";
}
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Dec 28 '18 at 5:11









Mohammed HossainMohammed Hossain

1




1












  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Dang Nguyen
    Dec 28 '18 at 5:35










  • Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
    – aliusman
    Dec 28 '18 at 5:35


















  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Dang Nguyen
    Dec 28 '18 at 5:35










  • Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
    – aliusman
    Dec 28 '18 at 5:35
















While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Dang Nguyen
Dec 28 '18 at 5:35




While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Dang Nguyen
Dec 28 '18 at 5:35












Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
– aliusman
Dec 28 '18 at 5:35




Hi, Welcome and please always add Explanation of your code when answering a question. You can edit your post and add more information.
– aliusman
Dec 28 '18 at 5:35


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • 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.


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





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • 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.


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%2fstackoverflow.com%2fquestions%2f10804148%2ffinding-paths-in-a-undirected-graph%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

Mossoró

Error while reading .h5 file using the rhdf5 package in R

Pushsharp Apns notification error: 'InvalidToken'