Java Easy Peasy BFS Solution


#1
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Solution {
    int boardLen;
    int boardWidth;
    boolean[][] visited;

    class Move {
        final int i;
        final int j;
        final int dist;

        public Move(int i, int j, int dist) {
            this.i = i;
            this.j = j;
            this.dist = dist;
        }

        boolean isValid() {
            return (i > 0 && i < boardLen) && (j > 0 && j < boardWidth) && !visited[i][j];
        }

        List<Move> getNextMoves() {
            return Stream.of(
                    new Move(i - 2, j - 1, dist + 1),
                    new Move(i - 2, j + 1, dist + 1),
                    new Move(i + 2, j - 1, dist + 1),
                    new Move(i + 2, j + 1, dist + 1),
                    new Move(i - 1, j - 2, dist + 1),
                    new Move(i + 1, j - 2, dist + 1),
                    new Move(i - 1, j + 2, dist + 1),
                    new Move(i + 1, j + 2, dist + 1)
            ).filter(Move::isValid).peek(move -> visited[move.i][move.j] = true).collect(Collectors.toList());
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Move)) return false;
            Move move = (Move) o;
            return i == move.i && j == move.j;
        }

        @Override
        public int hashCode() {
            return Objects.hash(i, j);
        }
    }

    public int knight(int A, int B, int C, int D, int E, int F) {
        boardLen = A + 1;
        boardWidth = B + 1;

        visited = new boolean[boardLen][boardWidth];
        Move dest = new Move(E, F, -1);

        Queue<Move> q = new ArrayDeque<>();
        visited[C][D] = true;
        q.add(new Move(C, D, 0));

        while (!q.isEmpty()) {
            Move u = q.remove();
            if (u.equals(dest)) return u.dist;
            q.addAll(u.getNextMoves());
        }

        return -1;
    }
}