714000. Knight in Geekland

Medium

Knight in Geekland

Summary

The Knight in Geekland problem involves a knight that moves around a chessboard. The goal is to find the shortest path for the knight to reach all squares on the board, ensuring that each square is visited exactly once. This problem requires an understanding of dynamic programming and graph traversal techniques.

Detailed Explanation

To solve this problem, we can use a combination of Breadth-First Search (BFS) and dynamic programming. The key idea is to keep track of the minimum distance from the starting point to reach each square on the board.

Here's a step-by-step breakdown of the solution:

  1. Initialize an n x n matrix dp with all values set to infinity, where n is the size of the chessboard.
  2. Set the value of dp[0][0] to 0, as this is the starting point for our knight's journey.
  3. Perform a BFS traversal from the starting point (0, 0). For each cell (i, j) that we visit, check if it's already been visited and if not, update its value in dp.
  4. When visiting a cell, consider all possible moves of the knight (8 directions: horizontal, vertical, and diagonal) and calculate the minimum distance to reach each adjacent cell.
  5. Update the values in dp based on the calculated distances.
  6. Repeat step 3 until all cells have been visited.
  7. The final value in dp represents the shortest path for the knight to visit all squares on the board.

Time complexity: O(n^2), where n is the size of the chessboard. Space complexity: O(n^2) for the dp matrix.

Optimized Solutions

Java

View on GeeksforGeeks
public class KnightInGeekland {
    public static void main(String[] args) {
        int[][] dp = new int[8][8];
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                dp[i][j] = Integer.MAX_VALUE;
            }
        }
        dp[0][0] = 0;
        // Perform BFS traversal
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (dp[i][j] == 0) {
                    // Calculate distances for adjacent cells
                    for (int k = -2; k <= 2; k++) {
                        for (int l = -2; l <= 2; l++) {
                            int x = i + k;
                            int y = j + l;
                            if (x >= 0 && x < 8 && y >= 0 && y < 8) {
                                dp[x][y] = Math.min(dp[x][y], dp[i][j] + 1);
                            }
                        }
                    }
                }
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.