Creating a maze solving algorithm in Java

前端 未结 5 1460
萌比男神i
萌比男神i 2021-02-01 10:56

I\'ve been assigned with the task of creating a maze solver in Java. Here\'s the assignment:

Write an application that finds a path through a maze.  
The maze sh         


        
5条回答
  •  长情又很酷
    2021-02-01 11:27

    I tried to implement this using DFS algorithm utilizing some Java OOP concepts.

    See complete solution on my github repository

    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();
    

    }

提交回复
热议问题