Untitled

 avatar
unknown
typescript
a year ago
2.8 kB
8
Indexable
type Station = string;
type Line = {
    name: string;
    stations: Station[];
};

const metroLines: Line[] = [
    { name: "M1", stations: ["Yenikapı", "Aksaray", "Topkapı", "Otogar", "Kocatepe", "Esenler", "Kirazlı"] },
    { name: "M2", stations: ["Yenikapı", "Haliç", "Şişhane", "Taksim", "Osmanbey", "Şişli", "Gayrettepe", "Levent", "4.Levent"] },
    { name: "M3", stations: ["Kirazlı", "Bağcılar", "Mahmutbey", "İstoç", "İkitelli", "Olimpiyat"] },
    { name: "M4", stations: ["Kadıköy", "Ayrılık Çeşmesi", "Acıbadem", "Ünalan", "Göztepe", "Kozyatağı", "Bostancı", "Kartal", "Pendik"] },
    { name: "M5", stations: ["Üsküdar", "Fıstıkağacı", "Bağlarbaşı", "Altunizade", "Ümraniye", "Çekmeköy"] },
    // Diğer hatlar ve duraklar eklenebilir
];

function getConnectedStations(station: Station, lines: Line[]): Station[] {
    const connectedStations: Station[] = [];
    for (const line of lines) {
        const index = line.stations.indexOf(station);
        if (index !== -1) {
            if (index > 0) {
                connectedStations.push(line.stations[index - 1]);
            }
            if (index < line.stations.length - 1) {
                connectedStations.push(line.stations[index + 1]);
            }
        }
    }
    return connectedStations;
}

function findRoute(start: Station, end: Station, lines: Line[]): { route: Station[], transfers: Station[] } {
    let visited: { [key: string]: boolean } = {};
    let queue: { station: Station, path: Station[], transfers: Station[] }[] = [{ station: start, path: [start], transfers: [] }];

    while (queue.length > 0) {
        let { station, path, transfers } = queue.shift()!;
        if (station === end && transfers.length <= 3) return { route: path, transfers };

        if (!visited[station]) {
            visited[station] = true;

            let connectedStations = getConnectedStations(station, lines);
            for (let connectedStation of connectedStations) {
                if (!visited[connectedStation]) {
                    let newTransfers = [...transfers];
                    if (path.length > 1 && path[path.length - 2] !== connectedStation) {
                        newTransfers.push(station);
                    }
                    queue.push({ station: connectedStation, path: [...path, connectedStation], transfers: newTransfers });
                }
            }
        }
    }
    return { route: [], transfers: [] };
}

// Test
const startStation: Station = "4.Levent";
const endStation: Station = "Ünalan";
const result = findRoute(startStation, endStation, metroLines);

console.log(`Route from ${startStation} to ${endStation}:`, result.route);
console.log(`Transfers:`, result.transfers);
Editor is loading...
Leave a Comment