// まずTLEとなるでしょう・・・ import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String... args) throws Exception { Scanner sc = new Scanner(System.in); int w = sc.nextInt(); int h = sc.nextInt(); int n = sc.nextInt(); Map> map = new HashMap<>(); while (sc.hasNextInt()) { int m = sc.nextInt(); int b = sc.nextInt(); for (int i = 0; i < m; i++) { int bTo = sc.nextInt(); int offset; if (bTo >= b + w) { offset = w; } else if (bTo > b) { offset = 1; } else if (bTo <= b - w) { offset = -w; } else { offset = -1; } while (b != bTo) { map.computeIfAbsent(b, x -> new HashSet()); map.get(b).add(b + offset); map.computeIfAbsent(b + offset, x -> new HashSet()); map.get(b + offset).add(b); b += offset; } } } Queue queue = new LinkedList<>(); queue.add(new Point(0, 0)); Set visited = new HashSet<>(); visited.add(0); Point point; while ((point = queue.poll()) != null) { Set indexesTo = map.get(point.index); if (indexesTo != null) { for (Integer indexTo : indexesTo) { if (indexTo == w * h - 1) { System.out.println(point.move + 1); System.exit(0); } if (!visited.contains(indexTo)) { visited.add(indexTo); queue.add(new Point(indexTo, point.move + 1)); } } } } System.out.println("Odekakedekinai.."); } } class Point { final int index; final int move; Point(int index, int move) { this.index = index; this.move = move; } @Override public String toString() { return String.format("index: %d, move: %d", index, move); } }