/ LaberintoSolver.cs
LaberintoSolver.cs
 1  using Laberinto;
 2  using System;
 3  using System.Collections.Generic;
 4  using System.Linq;
 5  using System.Text;
 6  using System.Threading.Tasks;
 7  
 8  public class LaberintoSolver
 9  {
10      private int filas;
11      private int columnas;
12      private Casilla[,] laberinto;
13      private List<(int, int)> camino;
14  
15      private readonly int[] dx = { 1, -1, 0, 0 };  // movimientos en x
16      private readonly int[] dy = { 0, 0, 1, -1 };  // movimientos en y
17  
18      public LaberintoSolver(Casilla[,] laberinto)
19      {
20          this.laberinto = laberinto;
21          filas = laberinto.GetLength(0);
22          columnas = laberinto.GetLength(1);
23          camino = new List<(int, int)>();
24      }
25  
26      public bool DFS(int x, int y, int endX, int endY)
27      {
28          // Limites y condiciones base
29          if (x < 0 || y < 0 || x >= filas || y >= columnas) return false;
30          if (laberinto[x, y].colisionable || laberinto[x, y].visitada) return false;
31  
32          // Marcar la casilla como visitada
33          laberinto[x, y].visitada = true;
34  
35          // Añadir al camino actual
36          camino.Add((x, y));
37  
38          // Si es la casilla destino
39          if (x == endX && y == endY)
40              return true;
41  
42          // Explorar vecinos (arriba, abajo, izquierda, derecha)
43          for (int i = 0; i < 4; i++)
44          {
45              int nx = x + dx[i];
46              int ny = y + dy[i];
47  
48              if (DFS(nx, ny, endX, endY))
49                  return true;
50          }
51  
52          // Si no se encontró camino, retroceder
53          camino.RemoveAt(camino.Count - 1);
54          return false;
55      }
56  
57      public List<(int, int)> ObtenerCamino()
58      {
59          return camino;
60      }
61  }