C♯の勉強

C♯4.0 で TopCoder の過去問を解きます。

TopCoder SRM 583: TravelOnMars

public class TravelOnMars {
    struct Data {
        public int pos;
        public int step;
    }

    public int minTimes(int[] range, int startCity, int endCity) {
        Queue<Data> qu = new Queue<Data>();
        qu.Enqueue(new Data() { pos = startCity, step = 0 });
        var visited = new bool[range.Length];
        while (qu.Any()) {
            Data now = qu.Dequeue();
            if (now.pos == endCity) return now.step;
            if (visited[now.pos]) continue;
            visited[now.pos] = true;
            for (int i = 0; i < range.Length; i++) {
                int d = Math.Abs(i - now.pos);
                d = Math.Min(d, range.Length - d);
                if (d <= range[now.pos]) {
                    qu.Enqueue(new Data() { pos = i, step = now.step + 1 });
                }
            }
        }
        return -1;
    }
}