java – 查找可能的节点关于骰子值

我想编写一个递归算法,根据骰子值突出显示所有可能的节点.

我怎样才能做到这一点 ?不应该从空节点移动.

在您可以看到的图像中,我当前的节点是蓝色的,例如当骰子值为4时,我想突出显示红色位置.我写了这样的代码但不起作用提前谢谢

f(node n, dice d){

  if(d == 0)
    n.setDest();

  if(Up node != null)
    f(Up node , d-1);

  if(Down node !=null)
    f(Down node, d-1);

  if(Right node != null)
    f(Right node,d-1);

  if(Left node != null)
    f(Left node,d-1);

 }

最佳答案 这是一个非递归的解决方案

public class Move {
   private List<Node> steps;
   private int stepsRemaining;
   private Node lastStep;

   public Move(List<Node> steps, int stepsRemaining) {
      this.steps = steps;
      this.stepsRemaining = stepsRemaining;
      this.lastStep = steps.get(steps.size() - 1);
   }

   // getters and setters
}

public List<Node> getOptions(Node node, int steps) {
    LinkedList<Move> stack = new LinkedList<Move>();
    stack.addFirst(new Move(Arrays.asList(node), steps);

    List<Node> options = new ArrayList<Node>();
    while (!stack.isEmpty()) {
        Move currentMove = stack.removeFirst();
        Node lastStep = currentMove.lastStep;
        Node[] childNodes = new Node[] { lastStep.up, lastStep.down, lastStep.left, lastStep.right };
        for (Node childNode : childNodes) {
           // make sure we don't go back on ourselves
           if (childNode != null && !currentMove.steps.contains(childNode)) {
               if (currentMove.stepsRemaining == 1) {
                   options.add(childNode);
                   continue;
               }
               List<Node> childSteps = new ArrayList<Node>(currentNode.steps);
               childSteps.add(childNode);
               stack.addFirst(new Move(childSteps, currentMove.stepsRemaining - 1));
           }
        }
    }
    return options;
}
点赞