CONTOH VISUAL :
package javaapplication42;
import java.util.*;
public class DFSPathfinding {
static int[][] grid = {
{0, 1, 1, 9, 1},
{1, 2, 1, 1, 1},
{1, 9, 2, 9, 1},
{1, 1, 2, 1, 1},
{1, 1, 1, 2, 0} // 0 di sini = Start/Goal, 9 = dinding
};
static int rows = grid.length;
static int cols = grid[0].length;
static int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}}; // bawah, atas, kanan, kiri
static int bestCost = Integer.MAX_VALUE;
static List<String> bestPath = new ArrayList<>();
static boolean[][] visited = new boolean[rows][cols];
public static void main(String[] args) {
List<String> path = new ArrayList<>();
dfs(0, 0, 0, path); // Start di (0,0)
if (bestCost < Integer.MAX_VALUE) {
System.out.println("Biaya minimum: " + bestCost);
System.out.println("Jalur yang dilalui: " + bestPath);
} else {
System.out.println("Tidak ada jalur ditemukan.");
}
}
static void dfs(int x, int y, int cost, List<String> path) {
// Cek batas
if (x < 0 || x >= rows || y < 0 || y >= cols) return;
// Cek dinding atau sudah dikunjungi
if (grid[x][y] == 9 || visited[x][y]) return;
// Hitung biaya (S dan G dianggap 0)
int cellCost = (x == 0 && y == 0) || (x == rows-1 && y == cols-1) ? 0 : grid[x][y];
int newCost = cost + cellCost;
// Pruning
if (newCost >= bestCost) return;
// Tambahkan posisi ke path
path.add("(" + x + "," + y + ")");
visited[x][y] = true;
// Jika sampai Goal
if (x == rows-1 && y == cols-1) {
if (newCost < bestCost) {
bestCost = newCost;
bestPath = new ArrayList<>(path); // Simpan jalur terbaik
}
} else {
// Coba 4 arah
for (int[] d : directions) {
dfs(x + d[0], y + d[1], newCost, path);
}
}
// Backtrack
path.remove(path.size() - 1);
visited[x][y] = false;
}
}



0 komentar:
Posting Komentar