在“寻宝”中使用递归回溯10x10网格打印出正确的字符串

时间:2014-11-22 15:18:34

标签: java recursion

有一个10乘10的网格填充数字。用户可以在网格上的某个位置启动,它们可以向上,向下,向左或向右移动。它们当前所在的数字对应于它们向上,向下,向左或向右移动的空间数量。目标是到达左上角或右上角或左下角或右下角。

我有一个递归方法,但是当我想要打印需要采用的路径的输出时,输出应该看起来像,没有引号,"上,下,左,上,下&#34 ;

我的问题是如何编写这个并且在字符串的末尾没有额外的逗号?我的输入总是出现"上,下,左,上,下,"用额外的逗号。我知道它是因为我的字符串打印输出我把逗号但是我如何在递归方法中有一个if语句,它不会为最后一步添加逗号。

我的代码如下:

public String findSolution() {
    // Call recursive method from here and return the string
    // representing the path.

    return backtrack(5, 5, "");
}

/**
 * Recursive backtracking method for finding a path from a starting point.
 * 
 * @param row
 *            - row of starting point
 * @param col
 *            - column of starting point
 * @param pathSoFar
 *            - the current path so far.
 * @return whether a path was found
 */
public String backtrack(int row, int col, String pathSoFar) {
    booleanArray[row][col] = true;
    if (winningCond(row,col) == true) {
        return pathSoFar;
    } else {
        steps = map[row][col];

        /**
         * try up.
         */

        if(offBoard(row - steps, col) == false 
                && booleanArray[row - steps][col] != true) {
            return pathSoFar = backtrack(row 
                    - steps, col, pathSoFar + "up");
        }
        /**
         * if that didn't work try right.
         */

        else if(offBoard(row, col + steps) == false 
                && booleanArray[row][col + steps] != true) {
            return pathSoFar = backtrack(row, col + steps, 
                    pathSoFar + "right");           
        }

        /**
         * if that didn't work try down.
         */

        else if(offBoard(row + steps, col) == false 
                && booleanArray[row + steps][col] != true) {
            return pathSoFar = backtrack(row + steps, col, 
                    pathSoFar + "down");            
        }

        /**
         * if that didn't work try left.
         */
        else if(offBoard(row, col - steps) == false 
                && booleanArray[row][col - steps] != true) {
            return pathSoFar = backtrack(row, col - steps, 
                    pathSoFar + "left");            
        } else {
            return null;
        }
    }
}

0 个答案:

没有答案