实施深度优先搜索时的scilab错误21

时间:2014-11-17 15:01:53

标签: graph depth-first-search scilab

我正在尝试在 scilab 中实现深度优先搜索,以查找两个节点之间的所有路径。

我收到一条错误消息:error 21 Invalid index。我试图在这里和其他地方找到解决方案,但我找不到一个。

我的问题:任何人都可以在我的代码中找到错误吗?或者,我做错了方法,我应该采取不同的方式。我的最终目标是使用此方法在大约1800个节点的图形中找到两个节点之间的所有路径

我的代码是:

    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

我这样称呼它:

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);

旁白:我是stackoverflow的新手。如果我正在做违反规则或惯例的事情,请告诉我,我会尽力在现在或将来修复它。

提前感谢任何建议。 Paulien

2 个答案:

答案 0 :(得分:1)

感谢答案,我现在拥有正常运行的代码。我在这里发布最终代码,以防其他任何人搜索此问题并发现它有用。

功能:

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

要调用此函数,请使用:

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);

这将打印起始节点与文件之间的所有路径。

答案 1 :(得分:0)

似乎是一个范围问题。

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

1覆盖全局变量。为确保不会发生这种情况,请在dfs函数中将其声明为global

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