pauw13
pauw13

Reputation: 11

scilab error 21 when implementing depth-first search

I am trying to implement a depth first search in scilab, to find all paths between two nodes.

I am getting an error message: error 21 Invalid index. I have tried to find a solution here and in some other places, and I could not find one.

My question: can anyone find the error in my code? Or alternatively, am I doing the method wrong and should I be doing it differently. My ultimate goal with this is to use this method to find all paths between two nodes in a graph of about 1800 nodes.

My code is:

    function [x] = dfs(node)

     if node==j then

  //print path to file
  [nrRows,nrCols]=size(path)

  for counter=1:nrCols
   mfprintf(o1,'%d ',path(1,counter))
  end

  mfprintf(o1,'\n')
 else
  visited(1,node)=1;
  path=[path,node]

  for nr=1:n
   if v(node,nr)==1 then //node en nr zijn neighbours
    if visited(1,nr)==0 then
     [y]=dfs(nr)
    end
    visited(1,nr)=0
    path(:,$)=[] //verwijder laatste element uit path
   end
  end //for nr
 end 
x=1
endfunction

And I am calling it like this:

n=4;
v=[ 0 1 1 0;
    1 0 1 0;
    1 1 0 1;
    0 0 1 0];

i=1; //starting node
j=3; //end node
visited=zeros(1,n);
path=zeros(1,1);
o1 = mopen('pathsBetweenTwoNodes', 'w');
[a]=dfs(i);

Asides: I am new to stackoverflow. If I am doing something that is against the rules or customs please tell me and I will do my best to fix it now or in the future.

Thanks in advance for any advice. Paulien

Upvotes: 0

Views: 289

Answers (2)

pauw13
pauw13

Reputation: 11

Thanks to the answer I now have code that works correctly. I am posting the final code here in case anyone else ever searches for this problem and finds it useful.

The function:

function dfs(node)
 global visited
 global path

 if node==j then 
  if path(1,1)==0 then
   path(1,1)=node
  else
   path=[path,node]
  end
  [nrRows,nrCols]=size(path)
  for counter=1:nrCols
   mfprintf(o1,'%d ',path(1,counter))
  end
  mfprintf(o1,'\n')

 else // node!=j

  visited(1,node)=1;
  if path(1,1)==0 then
   path(1,1)=node
  else
   path=[path,node]
  end

  for nr=1:n
   if v(node,nr)==1 then //node and nr are neighbours
    if visited(1,nr)==0 then
     dfs(nr)
    end
   end
  end //for nr
 end

 //visited(1,nr)=0
 visited(1,node)=0
 path(:,$)=[] //remove last element from path

endfunction

To call this function use:

n=4;
v=[ 0 1 1 0;
1 0 1 0;
1 1 0 1;
0 0 1 0];

i=1; //startnode
j=3; //endnode

global visited
visited=zeros(1,n);
global path
path=zeros(1,1);

o1 = mopen('pathsBetweenTwoNodes.txt', 'w');

dfs(i);

This prints all paths between the start en end node to a file.

Upvotes: 1

spoorcc
spoorcc

Reputation: 2955

Seems to be a scoping issue.

...
visited(1,node)=1; 
...

Overwrites the global variable with a 1. To make sure this does not happen, declare it as a global inside the dfs function.

...
global visited
visited(1,node)=1;
...

Upvotes: 0

Related Questions