Introducción

1

¿Qué es un grafo?

2

¿Qué es un árbol?

3

¿Qué es recursión?

4

Aplicaciones reales de grafos y árboles

5

Formas de representar un grafo

DFS

6

Análisis de DFS: algoritmo de búsqueda en profundidad

7

Programando DFS de forma recursiva

8

Otras formas de programar DFS

9

Recorridos y profundidad de un Árbol

10

Sum Root to Leaf Numbers: análisis del problema

11

Solución de Sum Root to Leaf Numbers

12

Playground: Sum Root to Leaf Numbers

13

Programando Sum Root to Leaf Numbers en Golang

14

Number of Islands: análisis del problema

15

Solución de Number of Islands

16

Playground: Number of Islands

17

Programando Number of Islands en Python

18

Ejercicios recomendados de DFS

19

Ejercicios resueltos de DFS

BFS

20

Análisis de BFS: algoritmo de búsqueda en anchura

21

Programando BFS con Python

22

Minimum Knights Moves (movimientos de caballo en ajedrez): análisis del problema

23

Solución de Minimum Knights Moves

24

Playground: Minimum Knights Moves

25

Programando Minimum Knights Moves con Python

26

Rotting Oranges: análisis del problema

27

Solución de Rotting Oranges

28

Playground: Rotting Oranges

29

Rotting Oranges con Java

30

Shortest Bridge Between Islands: análisis del problema

31

Solución de Shortest Bridge Between Islands

32

Playground: Shortest Bridge Between Islands

33

Programando Shortest Bridge Between Islands con Python

34

Ejercicios recomendados de BFS

35

Ejercicios resueltos de BFS

Backtrack

36

Algoritmo de Backtrack

37

Letter Combinations of a Phone Number: análisis del problema

38

Solución de Letter Combinations of a Phone Number

39

Programando Letter Combinations of a Phone Number con C++

40

Playground: Letter Combinations of a Phone Number

41

Restore IP Addresses: análisis del problema

42

Programando Restore IP Addresses con C++

43

Playground: Restore IP Addresses

44

Word Search: análisis del problema

45

Solución de Word Search

46

Playgrund: Word Search

47

Programando Word Search JavaScript

48

Reto: N Queens Puzzle

49

Ejercicios recomendados de Backtrack

50

Ejercicios resueltos de Backtrack

Próximos pasos

51

¿Qué otros algoritmos y tipos de grafos puedes aprender?

52

¿Quieres más cursos avanzados de algoritmos?

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Solución de Minimum Knights Moves

23/52
Recursos

Aportes 3

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

No es el mas efectivo pero es trabajo honesto :V

import math

MOVEMENTS = [
    (2, 1), (1, 2), (-2, 1), (-1, 2),
    (2, -1), (1, -2), (-2, -1), (-1, -2)
]


def distance_between_points(x1, y1, x2, y2):
    return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)


def move_point(x: int, y: int, search_point: tuple, previous_point, previous_distance=0):
    list_possible_moves = []
    for movement_index in range(0, len(MOVEMENTS)):
        next_x = x + MOVEMENTS[movement_index][0]
        next_y = y + MOVEMENTS[movement_index][1]
        distance = distance_between_points(next_x, next_y, search_point[0], search_point[1])
        if distance == 0:
            return None
        if (next_x >= search_point[0] and next_y >= search_point[1]) \
                or (distance > distance_between_points(0, 0, search_point[0], search_point[1])):
            continue

        list_possible_moves.append([next_x, next_y, previous_distance + distance, previous_point + [(next_x, next_y)]])
    list_possible_moves.sort(key=lambda x: x[2])
    return list_possible_moves


def horse_steps(x, y):
    initial = [[0, 0]]
    jumps = 1
    while jumps < 1000:
        jumps = jumps + 1
        next_step = []
        for step in initial:
            response = move_point(x=step[0], y=step[1], search_point=(x, y), previous_point=[(step[0], step[1])])
            if response is None:
                return jumps
            next_step = next_step + response
            if next_step is None:
                print('No more steps')
                break
            initial = next_step


if __name__ == '__main__':
    assert horse_steps(2, 1) == 2
    assert horse_steps(5, 5) == 5
    assert horse_steps(5, 0) == 4

código en Python: `from queue import Queue` `from typing import List` `class Solution:` ` def minimum_knight_moves(self, target: List[int]) -> int:` ` # The knight moves in 8 possible directions` ` directions = [` ` (2, 1), (2, -1), (-2, 1), (-2, -1),` ` (1, 2), (1, -2), (-1, 2), (-1, -2)` ` ]` ` queue = Queue()` ` queue.put((0, 0, 0)) # (current_x, current_y, step_count)` ` visited_positions = set()` ` visited_positions.add((0, 0))` ` target_x, target_y = abs(target[0]), abs(target[1])` ` # BFS algorithm` ` while not queue.empty():` ` # Dequeue the next position and step count to be processed` ` current_x, current_y, current_steps = queue.get()` ` # Check if we've reached the target position` ` if current_x == target_x and current_y == target_y:` ` return current_steps` ` # Explore all possible knight moves` ` for dx, dy in directions:` ` new_x = current_x + dx` ` new_y = current_y + dy` ` new_position = (abs(new_x), abs(new_y))` ` # Check if the new position has been visited` ` if new_position not in visited_positions:` ` visited_positions.add(new_position)` ` queue.put((new_x, new_y, current_steps + 1))` `# Example usage:` `solution = Solution()` `print(solution.minimum_knight_moves([2, 1])) # Output: 1` `print(solution.minimum_knight_moves([5, 5])) # Output: 4`
Esta es mi solución en java, no estoy seguro de si es la mas eficiente (ya que para cada nivel calcula todas las nuevas posiciones posibles posibles) pero funciona, ¿alguna recomendación? ```js public class MinimumKnightsMoves { public static void main(String[] args) { System.out.println("Welcome to Minimum knights moves!"); System.out.println("in here you can calculate the minimum moves a chess knight needs to move from x,y point to another coordinates in an infinite chess board."); System.out.print("please insert the x coordinate for the initial position: "); final int startX = scanner.nextInt(); System.out.print("please insert the y coordinate for the initial position: "); final int startY = scanner.nextInt(); System.out.println("now you need to insert the destination coordinates..."); System.out.print("insert the x destination coordinate: "); final int destinationX = scanner.nextInt(); System.out.print("insert the y destination coordinate: "); final int destinationY = scanner.nextInt(); System.out.printf("the minimum moves to move from [%d,%d] to [%d,%d] are: [%d]", startX, startY, destinationX, destinationY, calculateMoves(startX, startY, destinationX, destinationY)); } private static int calculateMoves(int startX, int startY, int destinationX, int destinationY) { int moves = 0; if(startX == destinationX && startY == destinationY){ return moves; } Queue<int[]> movements = getPossibleMovementsForKnight(startX, startY); while(!movements.isEmpty()){ moves++; Queue<int[]> newMovements = new LinkedList<>(); while(!movements.isEmpty()) { int[] actualMove = movements.poll(); if (actualMove[0] == destinationX && actualMove[1] == destinationY) { return moves; } newMovements.addAll(getPossibleMovementsForKnight(actualMove[0], actualMove[1])); } movements.addAll(newMovements); } return moves; } private static Queue<int[]> getPossibleMovementsForKnight(int startX, int startY) { System.out.printf("Possible movements for knight at [%d,%d] are: \n", startX, startY); Queue<int[]> moves = new LinkedList<>(); moves.add(new int[] {startX + 2, startY + 1}); System.out.printf("\t [%d,%d]\n", startX + 2, startY + 1); moves.add(new int[] {startX + 1, startY + 2}); System.out.printf("\t [%d,%d]\n", startX + 1, startY + 2); moves.add(new int[] {startX - 2, startY + 1}); System.out.printf("\t [%d,%d]\n", startX - 2, startY + 1); moves.add(new int[] {startX - 1, startY + 2}); System.out.printf("\t [%d,%d]\n", startX - 1, startY + 2); moves.add(new int[] {startX + 2, startY - 1}); System.out.printf("\t [%d,%d]\n", startX + 2, startY - 1); moves.add(new int[] {startX + 1, startY - 2}); System.out.printf("\t [%d,%d]\n", startX + 1, startY - 2); moves.add(new int[] {startX - 2, startY - 1}); System.out.printf("\t [%d,%d]\n", startX - 2, startY - 1); moves.add(new int[] {startX - 1, startY - 2}); System.out.printf("\t [%d,%d]\n", startX - 1, startY - 2); return moves; } } ```