using System;
using System.Collections.Generic;
namespace DevilLink2.Core
{
public sealed class LinkPathFinder
{
private static readonly int[] Dr = { -1, 1, 0, 0 };
private static readonly int[] Dc = { 0, 0, -1, 1 };
private sealed class Node
{
public readonly GridPosition Position;
public readonly int Direction, Turns;
public readonly Node Parent;
public Node(GridPosition position, int direction, int turns, Node parent)
{ Position = position; Direction = direction; Turns = turns; Parent = parent; }
}
/// Returns endpoints and key corners, including border coordinates.
/// Invalid/empty endpoints return false. The board is never mutated.
public bool TryFindPath(Board board, GridPosition start, GridPosition target,
out IReadOnlyList path)
{
if (board == null) throw new ArgumentNullException(nameof(board));
path = Array.Empty();
if (start == target || !board.Contains(start.Row, start.Column) ||
!board.Contains(target.Row, target.Column)) return false;
var a = board.GetTile(start.Row, start.Column);
var b = board.GetTile(target.Row, target.Column);
if (a == null || b == null || a.Symbol != b.Symbol) return false;
var visited = new bool[board.Rows + 2, board.Columns + 2, 4, 3];
var queue = new Queue();
var origin = new Node(start, -1, 0, null);
for (int d = 0; d < 4; d++) Enqueue(origin, d, 0, board, target, visited, queue);
while (queue.Count > 0)
{
var current = queue.Dequeue();
if (current.Position == target) { path = BuildPath(current); return true; }
for (int d = 0; d < 4; d++)
{
int turns = current.Turns + (d == current.Direction ? 0 : 1);
if (turns <= 2) Enqueue(current, d, turns, board, target, visited, queue);
}
}
return false;
}
private static void Enqueue(Node parent, int direction, int turns, Board board,
GridPosition target, bool[,,,] visited, Queue queue)
{
var next = new GridPosition(parent.Position.Row + Dr[direction], parent.Position.Column + Dc[direction]);
if (next.Row < -1 || next.Row > board.Rows || next.Column < -1 || next.Column > board.Columns) return;
if (next != target && board.Contains(next.Row, next.Column) && !board.IsEmpty(next.Row, next.Column)) return;
if (visited[next.Row + 1, next.Column + 1, direction, turns]) return;
visited[next.Row + 1, next.Column + 1, direction, turns] = true;
queue.Enqueue(new Node(next, direction, turns, parent));
}
private static IReadOnlyList BuildPath(Node end)
{
var full = new List();
for (var n = end; n != null; n = n.Parent) full.Add(n.Position);
full.Reverse();
var corners = new List { full[0] };
for (int i = 1; i < full.Count - 1; i++)
{
var a = full[i - 1]; var b = full[i]; var c = full[i + 1];
if ((b.Row - a.Row != c.Row - b.Row) || (b.Column - a.Column != c.Column - b.Column))
corners.Add(b);
}
corners.Add(full[full.Count - 1]);
return corners.AsReadOnly();
}
}
}