达到一定条件后终止递归

时间:2018-03-19 12:38:57

标签: matlab recursion

我一直在尝试使用递归的Sudoku解算器。我遇到的问题是找到正确解决方案后的递归函数不会终止,但会继续,直到在每个位置测试每个数字。

如何在Matlab中终止这样的循环?函数中的错误条件'错误('...')可以破坏执行,但绝不是解决我的问题的好方法。

下面是类似递归的示例代码,为1到4的数字生成所有可能的2个元素向量。我希望它在两个数字都等于2时停止。

%possible moves at each position
moveMat = zeros([1,2])+3;

lineInput = zeros([1,2]);

%start recursion
recurNumbers(moveMat, 0, lineInput)

function recurNumbers(moveMat, position, lineVariable)

position = position + 1;

%if all numbers are equal to 2 then try to exit the function
if ~all(lineVariable == 2)

    %if all numbers are not equal to 2, try other combination
    if position < length(lineVariable)+1
        for move = 0 : moveMat(position)

            moveMat(position) = move;
            lineVariable(position) = lineVariable(position) + 1;
            recurNumbers(moveMat,position,lineVariable)
            disp(lineVariable)

        end
    end

else

    disp(lineVariable)
    return

end
end

现在它将两次打印矢量'[2 2]',这表示它识别了条件,但'return'将不会按照我的想象去做。

1 个答案:

答案 0 :(得分:-1)

虽然我不太清楚你想要达到的目标,但我认为以下功能符合你的停止标准。

function exit_fl = recurNumbers(moveMat, position, lineVariable)

exit_fl = 0;
if (all(lineVariable == 2)) 
  % Show the result and exit
  disp(lineVariable)
  exit_fl = 1;

else
  position = position + 1;
    %if all numbers are not equal to 2, try other combination
    if position < length(lineVariable)+1
        for move = 0 : moveMat(position)

            moveMat(position) = move;
            lineVariable(position) = lineVariable(position) + 1;
            % Receive the exit status of your function
            ex_fl = recurNumbers(moveMat,position,lineVariable);
            if (ex_fl == 1)
              % If the criterion was met, then stop
              exit_fl = 1;
              return
            end
        end
    end
end
end