Minimum Dice Throws with BFS Algorithm in Java

Snakes & Ladders — Minimum Dice Throws (Board → Graph) 💡 Graph View Each cell = node From cell i → edges to i+1 … i+6 Snake / Ladder = edge jump BFS gives minimum dice throws. --- ✅ Java Code (with example) import java.util.*; public class SnakesAndLaddersExample { static int minDiceThrows(int[] board) { int n = board.length; boolean[] visited = new boolean[n]; Queue<int[]> q = new LinkedList<>(); q.add(new int[]{0, 0}); // {cell, moves} visited[0] = true; while (!q.isEmpty()) { int[] cur = q.remove(); int cell = cur[0], moves = cur[1]; if (cell == n - 1) return moves; for (int dice = 1; dice <= 6 && cell + dice < n; dice++) { int next = cell + dice; if (board[next] != -1) next = board[next]; // jump via snake/ladder if (!visited[next]) { visited[next] = true; q.add(new int[]{next, moves + 1}); } } } return -1; } public static void main(String[] args) { int[] board = new int[30]; Arrays.fill(board, -1); // ladder 2 → 21 board[2] = 21; // snake 26 → 0 board[26] = 0; System.out.println("Minimum Dice Throws = " + minDiceThrows(board)); } } 🧪 Output Minimum Dice Throws = 3 🧠 BFS Meaning Each level = 1 dice roll Shortest path → minimum throws #DSA #DataStructuresAndAlgorithms #Coding #Programmer #LeetCode #CodeEveryday #JavaDSA #CodingPractice #ProblemSolving #CP #CompetitiveProgramming #DailyCoding #TechJourney #CodingCommunity #DeveloperLife #100DaysOfCode #CodeWithMe #LearnToCode #GeekForGeeks #CodingMotivation

To view or add a comment, sign in

Explore content categories