web-dev-qa-db-ja.com

Java)で迷路解決アルゴリズムを作成する

私はJavaで迷路ソルバーを作成するタスクを割り当てられました。割り当ては次のとおりです。

Write an application that finds a path through a maze.  
The maze should be read from a file.  A sample maze is shown below.

O O O O O X O
X X O X O O X
O X O O X X X
X X X O O X O
X X X X O O X
O O O O O O O
X X O X X X O

文字「X」は壁またはブロックされた位置を表し、文字「O」は開いた位置を表します。迷路への入り口は常に右下隅にあり、出口は常に左上隅にあると考えることができます。プログラムはその出力をファイルに送信する必要があります。パスが見つかった場合、出力ファイルにはパスが含まれている必要があります。パスが見つからない場合は、メッセージをファイルに送信する必要があります。迷路には複数のソリューションパスがある場合がありますが、この演習では、すべてのソリューションではなく、1つのソリューションのみを見つけるように求められることに注意してください。

プログラムはスタックを使用して、探索しているパスを記録し、ブロックされた位置に到達したときにバックトラックする必要があります。

コードを書く前に、必ず完全なアルゴリズムを書いてください。割り当てを完了するのに役立つ追加のクラスを自由に作成してください。

Here's my Algorithm:
1)Initialize array list to hold maze
2)Read text file holding maze in format
    o x x x x o
    o o x o x x
    o o o o o x
    x x x x o o
3)Create variables to hold numbers of columns and rows
3)While text file has next line
    A. Read next line
    B. Tokenize line
    C. Create a temporary ArrayList
    D. While there are tokens
        i. Get token
        ii. create a Point
        iii. add point to temp ArrayList
        iv. increment maximum number of columns
    E. Add temp to maze arraylist, increment max rows
    F. initialize a hold of points as max rows - 1
    G. Create a start point with x values as maximum number of rows - 1, and y values as maximum number of columns - 1
    H. Create stack of points and Push starting location
    I. While finished searching is not done
        i. Look at top of stack and check for finish
        ii. check neighbors
        iii. is there an open neighbor?
            - if yes, update flags and Push
            - if no, pop from stack
    J. Print solution
4. Done is true

とにかく、私が設定したのは、示されているようにブール値を返すすべての基本的な方向に移動するためのset/getメソッドを持つPointsクラスです。

public class Points<E>
{
private int xCoord;
private int yCoord;
private char val;
private boolean N;
private boolean S;
private boolean E;
private boolean W;

public Points()
{
    xCoord =0;
    yCoord =0;
    val =' ';
    N = true;
    S = true;
    E = true;
    W = true;

}

public Points (int X, int Y)
{
        xCoord = X;
        yCoord = Y;

}

public void setX(int x)
{
    xCoord = x;
}
public void setY(int y)
{
    yCoordinate = y;
}

public void setNorth(boolean n)
{
    N = n;
}
public void setSouth(boolean s)
{
    S= s;
}
public void setEast(boolean e)
{
    E = e;
}

public void setWest(boolean w)
{
    W = w;
}

public int getX()
{
    return xCoord;

}

public int getY()
{
    return yCoord;
}
public char getVal()
{
    return val;
}

public boolean getNorth()
{
    return N;
}
public boolean getSouth()
{
    return S;
}

public boolean getEast()
{
    return E;
}
public boolean getWest()
{
    return W;
}

public String toString1()
{
    String result = "(" + xCoord + ", " +yCoord + ")";
    return result;
}

}

メインで実際の解決策を理解するのに問題があります。これが私が持っているものです:

import Java.io.*;
import Java.util.*;
import Java.lang.*;
import Java.text.*;


public class MazeSolve1
{
  public static void main(String[] args)
  {
//Create arrayList of Points
ArrayList<ArrayList<Points>> MAZE = new ArrayList<ArrayList<Points>>();
Scanner in = new Scanner(System.in);

//Read File in
System.out.print("Enter the file name: ");
String fileName = in.nextLine();
fileName = fileName.trim();
FileReader reader = new FileReader(fileName+".txt");
Scanner in2 = new Scanner(reader);

//Write file out
FileWriter writer = new FileWriter("Numbers.out");
PrintWriter out = new PrintWriter(writer);
boolean done = false;
int maxCol = 0;
int maxRow = 0;

while(!done) {

    //creating array lists
    while (in2.hasNextLine()) {
        //Read next line
        String nextLine = in2.nextLine();
        //Tokenize Line
        StringTokenizer st = new StringTokenizer(nextLine, " ");
        //Create temp ArrayList
        ArrayList<ArrayList<Points>> temp = new ArrayList<ArrayList<Points>>();

        //While there are more tokens
        while (st.hasNextToken()) {
            String token = st.nextToken();
            Points pt = new Points();
            temp.add(pt);
            maxCol++
        }
        MAZE.add(temp);
        maxRow++;
    }

    //create hold arraylist for max rows of maze -1 
    //create variables for start x and y coordinates
    ArrayList<ArrayList<Points>> hold = new ArrayList<ArrayList<Points>>();
    hold = MAZE.get(maxRow - 1);
    int startColumn = hold.get(maxCol - 1);
    int startRow = hold.get(maxRow - 1);
    Point start = new Point();
    start.setX(startColumn);
    start.setY(startRow);

    //initialize stack, and Push the start position
    MyStack<Points> st = new ArrayStack<Points>();
    st.Push(start.toString1());
    //south and east of start are edges of array
    start.setSouth(false);
    start.setEast(false);

    //while your position is not equal to point (0,0) [finish]
    while (st.peek() != "(0, 0)") {

        //getting the next coordinate to the North
        int nextY = start.getY() - 1;
        int nextX = start.getX();

        //if character to the North is an O it's open and the North flag is true
        if (hold.get(nextY) = 'O' && start.getNorth() == true) {
            //set flags and Push coordinate
            start.setNorth(false);
            st.Push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the East
        nextX = start.getX() + 1;
        //if character to the East is a O and the East flag is true
        if (hold.get(nextX) = 'O' && start.getEast() == true) {
            //set flags and Push coordinate
            start.setEast(false);
            st.Push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the South
        nextY = start.getY() + 1;
        //if character to the South is a O and the West flag is true
        if (hold.get(nextY) = 'O' && start.getSouth() == true) {
            //set flags and Push coordinate
            start.setSouth(false);
            st.Push(start.toString1());
        }
        //else pop from stack
        else { st.pop() }

        //keep looping until the top of the stack reads (0, 0)
    }

done = true;
}

//Print the results
System.out.println("---Path taken---");   
for (int i = 0; i< st.size(); i++) {
    System.out.println(st.pop);
    i++
}

構文エラーは別として、皆さんは私にいくつかの助けを提供できますか?どうもありがとう。

7
Copernikush

enter image description here

私はここに同様の答えを提出しました C++の迷路解決アルゴリズム

それを解決するチャンスを得るには、次のことを行う必要があります。

  • Solve()ルーチンを作成し、それ自体を再帰的に呼び出します:
    • 1番目、2番目、3番目、...が真の場合Solveは解決策を見つけることに成功しました
    • 1番目、2番目、3番目、...にfalseが含まれている場合は、バックトラックして別の方法を見つける必要があります
  • 無限ループを避けるために、これまで行ったことのある場所のバッファを構築する必要があります
    • あなたが動きをするとき、それはそれにタブを保つ必要があります
    • 行き止まりになったら、悪い動きを消す必要があります
    • 推測で焼き付け、間違っている場合は削除することで、上記を実装できます

これがソリューションの擬似コードです。

boolean solve(int X, int Y)
{
    if (mazeSolved(X, Y))
    {
        return true;
    }

    // Test for (X + 1, Y)
    if (canMove(X + 1, Y))
    {
        placeDude(X + 1, Y);
        if (solve(X + 1, Y)) return true;
        eraseDude(X + 1, Y);
    }

    // Repeat Test for (X - 1, Y), (X, Y - 1) and (X, Y + 1)
    // ...

    // Otherwise force a back track.
    return false;
 }
13
Stephen Quan

あなたはおそらく モジュール あなたのプログラム-私が理解できるように、あなたはファイルから迷路を読み、同時にそれを解決しようとしています。

より良いアプローチは、プログラムを2つの異なる部分に分割することです。

  1. 入力ファイルを読み取り、すべてのデータを含むマトリックスを作成します
  2. 与えられた行列から迷路を解く

そうすることで、各パーツを個別にビルドしてテストするのに役立ちます。これにより、プログラムの信頼性が向上します。

迷路の解決は、単純な [〜#〜] bfs [〜#〜] で行うことができます。これは、アルゴリズムが最初に提案したものと似ています [〜#〜] dfs [〜#〜]

7
amit

Amitが言ったように、最初に迷路全体を読み、それを2次元配列として保存する必要があります。これにより、迷路を1行ずつ解決しなくても迷路全体を見ることができます。

最初に配列のサイズを見つける必要があるため、テキストファイルを文字列のリストに読み込む必要があります。

List<String> strs = new ArrayList<String>();

//Pseudocode, choose however you want to read the file
while(file_has_next_line) {
    strs.add(get_next_line);
}

リストのサイズは行数を示し、常にグリッドであると仮定すると、split()。length、(スペースのカウント+ 1)を使用するか、いずれかの文字列のシンボルをカウントして列の数を取得できます。 。

マップデータを保存する最も簡単な方法は、ブール値の2D配列を使用することです。 trueは壁で、falseは空のスペースです。

boolean[][] wallMap = new boolean[rows][cols];

for(int i = 0; i < wallMap.length; i++) {

    //Separate each symbol in corresponding line
    String[] rowSymbols = strs.get(i).split(" ");

    for(int j = 0; j < wallMap[i].length; j++) {

        //Ternary operator can be used here, I'm just keeping it simple
        if(rowSymbols[j].equals("X")) {
             wallMap[i][j] = true;
        } else {
             wallMap[i][j] = false;
        }

    }

}

マップデータが配列に格納されたので、マップをトラバースして選択するのがはるかに簡単になりました。既製のアルゴリズム(amitの回答を参照)を使用するか、独自のアルゴリズムを作成することができます。これは宿題なので、自分で考えてみてください。

楽しんで。

1
Hedja

いくつかのJava OOPの概念を利用して、DFSアルゴリズムを使用してこれを実装しようとしました。

私の完全な解決策を参照してください githubリポジトリ

private boolean solveDfs() {
    Block block = stack.peekFirst();
    if (block == null) {
        // stack empty and not reached the finish yet; no solution
        return false;
    } else if (block.equals(maze.getEnd())) {
        // reached finish, exit the program
        return true;
    } else {
        Block next = maze.getNextAisle(block);
        // System.out.println("next:" + next);
        if (next == null) {
            // Dead end, chose alternate path
            Block discard = stack.pop();
            discard.setInPath(false);
            // System.out.println("Popped:" + discard);
        } else {
            // Traverse next block
            next.setVisited(true);
            next.setInPath(true);
            stack.Push(next);
        }
    }
    return solveDfs();

}

0
Narain Mittal

プログラムを2つのフェーズに分ける必要があります。 1つ目は初期化で、迷路の説明とプレーヤーの初期位置を読みます。この後、ボードを表すデータ構造ができます。 2つ目は実際のゲームで、3つの抽象化が必要です。

  • プレイヤーの状態。あなたの場合、それは非常に単純で、ボード上の実際の位置です。
  • 環境である迷路そのもの。特定の位置にアクセスしたかどうか、アクセスした位置をマークする機能、目標はどこにあるか、次に到達可能なセルなどを示す機能が必要です。
  • 検索アルゴリズムであるロジック。

これらのいずれも、他のものをあまり変更せずに変更できるはずです。たとえば、検索アルゴリズムの改善を求められたり、複数の目標がある問題が発生したりする場合があります。現在の問題からわずかに変更された問題への切り替えの容易さは、プログラム設計の実際の測定基準です。

0
UmNyobe