From 5a1e12748274ffc87631124e6ae0d1a0a9f6c2e9 Mon Sep 17 00:00:00 2001 From: Andinus Date: Wed, 3 Nov 2021 17:13:15 +0530 Subject: java/DFS: Output in Fornax format --- algorithms/java/DFS.java | 91 +++++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 44 deletions(-) (limited to 'algorithms') diff --git a/algorithms/java/DFS.java b/algorithms/java/DFS.java index 671bfa8..61b2027 100644 --- a/algorithms/java/DFS.java +++ b/algorithms/java/DFS.java @@ -1,50 +1,46 @@ -public class CG_pathfinder { - static int paths = 0; - - private static final int[][] dir = new int[][]{ - {0, 1}, //right - {1, 0}, //down - {0, -1}, //left - {-1, 0} //up +public class DFS { + private static final int[][] directions = new int[][]{ + {+0, +1}, // Right. + {+1, +0}, // Down. + {+0, -1}, // Left. + {-1, +0}, // Up. }; static void traverse(int x, int y, char[][] maze, boolean[][] visited) { int curx; int cury; - for (int i = 0; i < 4; i++) { - // Print the maze at every iteration. - for(int j = 0; j < maze.length; j++) - for(int k = 0; k < maze[j].length; k++) - if (visited[j][k]) - System.out.print("x"); - else - System.out.print(maze[j][k]); - System.out.print(" "); - curx = x; - cury = y; - - curx += dir[i][0]; - cury += dir[i][1]; + for (int i = 0; i < 4; i++) { + curx = x + directions[i][0]; + cury = y + directions[i][1]; + // Out of bounds check. if (curx < 0 || cury < 0 || curx > maze.length - 1 || cury > maze.length - 1) - continue; //optional? //for square mazes + continue; - if (maze[curx][cury] == '$') { - paths++; + // Marker cells. + if (maze[curx][cury] == '$') System.out.print("|"); - // Print the maze at every iteration. - for(int j = 0; j < maze.length; j++) - for(int k = 0; k < maze[j].length; k++) - if (visited[j][k]) - System.out.print("x"); - else - System.out.print(maze[j][k]); - System.out.print(" "); - } else if (maze[curx][cury] == 'x' || visited[curx][cury]) + else if (maze[curx][cury] == '#') + System.out.print("!"); + + // Print the maze on every iteration. + for(int j = 0; j < maze.length; j++) + for(int k = 0; k < maze[j].length; k++) + if (j == curx && k == cury) + System.out.print("@"); + else + System.out.print(visited[j][k] ? "-" : maze[j][k]); + System.out.println(); + + // Found a solution, exiting. + if (maze[curx][cury] == '$') + System.exit(0); + + if (visited[curx][cury]) { continue; - else if (maze[curx][cury] == '_') { + } else if (maze[curx][cury] == '.') { visited[curx][cury] = true; traverse(curx, cury, maze, visited); visited[curx][cury] = false; @@ -54,20 +50,27 @@ public class CG_pathfinder { public static void main(String[] args) { char[][] maze = { - {'*', '#', '_'}, - {'_', '_', '_'}, - {'_', '_', '$'} + {'.', '#', '.'}, + {'.', '.', '.'}, + {'.', '.', '$'} }; - int[] start = {0, 0}; boolean[][] visited = new boolean[maze.length][maze[0].length]; - for (int i = 0; i< maze.length; i++) - for (int j = 0; j