通过2d数组Java生成路径

时间:2017-05-20 12:22:07

标签: java algorithm path

给定2D数组

|O|O|O|O|O|
|O|O|O|O|O|
|O|O|O|O|O|
|O|O|O|O|O|
|O|O|O|O|O|

我想通过它随机生成一条路径。下面是生成2D数组路径的代码

    public void generatePath() {
    //choose random start position
    Random ran = new Random();
    int row = ran.nextInt(this.Graph.length);
    int col = ran.nextInt(this.Graph.length);

    // add step in the beginning
    this.Graph[row][col] = Node.S;
    Path initial = new Path(row, col);
    this.path.add(initial);

    // since the length can differ
    int rowLength = this.Graph.length - 1;
    int columnLength = this.Graph[0].length - 1;
    // at each iteration make an array of possible moves
    String r = "right";
    String l = "left";
    String up = "up";
    String down = "down";

    //A list of choices 
    int choice = 0;
    ArrayList<String> choices = new ArrayList<String>();

    // total steps in path to generate
    int graphSize = Graph.length * Graph.length;
    int totalSs = graphSize*2;

    while (totalSs  > 0) {
        // add valid choices
        // check each move is within the size of the graph

        if (col < columnLength)
            choices.add(r);
        if (row < rowLength)
            choices.add(down);
        if (col > 0)
            choices.add(l);
        if (row > 0)
            choices.add(up);

       // choose a move randomly from the array
        choice = ran.nextInt(choices.size() - 1);
        String move = choices.get(choice);
        totalSs--;

        // perform move
        if (move.equalsIgnoreCase(r)) {
            this.Graph[row][col + 1] = Node.S;
            col += 1;

        }

        if (move.equalsIgnoreCase(l)) {
            this.Graph[row][col - 1] = Node.S;
            col -= 1;
        }
        if (move.equalsIgnoreCase(up)) {
            this.Graph[row - 1][col] = Node.S;
            row -= 1;
        }
        if (move.equalsIgnoreCase(down)) {
            this.Graph[row + 1][col] = Node.S;
            row += 1;
        }

        // add to path
        Path p = new Path(row, col);
        path.add(p);

        // clear array for next iteration
        choices.clear();
    }

}

目前,此代码存在两个问题 这是生成的示例路径 1)

 Path[0][1]
Path[1][1]
Path[1][0]
Path[1][1]
Path[1][0]
Path[1][1]
Path[1][0]
Path[1][1]
Path[1][0]

请注意它是如何生成一条不会返回行的路径的。 我如何更改代码以便它可以从行[0] - &gt; [1]转到并且能够返回到行[0]

2)许多步骤被浪费为回溯

0 个答案:

没有答案