LoginSignup
1
0

More than 5 years have passed since last update.

Dartでオフラインリアルタイムどう書く第四回の参考問題

Posted at

第四回 オフラインリアルタイムどう書くの参考問題をDartで解いてみました。
http://qiita.com/items/9c514267214d3917edf2

import "dart:math";

final List<int> xs = [0, 1, 0, -1];
final List<int> ys = [1, 0, -1, 0];
final int WIDTH = 5;
final int HEIGHT = 5;
final int shiftSize = (log(WIDTH * HEIGHT) / LN2).ceil().toInt();

main() {
  test("", 8512);
  test("af", 4256);
  test("xy", 4256);
  test("pq qr rs st di in ns sx", 184);
  test("af pq qr rs st di in ns sx", 92);
  test("bg ch di ij no st", 185);
  test("bc af ch di no kp mr ns ot pu rs", 16);
  test("ab af", 0);
  test("ty xy", 0);
  test("bg ch ej gh lm lq mr ot rs sx", 11);
  test("ty ch hi mn kp mr rs sx", 18);
  test("xy ch hi mn kp mr rs sx", 32);
  test("ch hi mn kp mr rs sx", 50);
  test("ab cd uv wx", 621);
  test("gh mn st lq qr", 685);
  test("fg gl lm mr rs", 171);
  print("ok");
}

test(String input, int expect) {
  assert(countPath(input) == expect);
}

int str2node(String chr) => chr.codeUnitAt(0) - "a".codeUnitAt(0);

int pos2node(int x, int y) => y * WIDTH + x;

int node2path(int from, int to) {
  return (from < to) ? (from << shiftSize) + to : (to << shiftSize) + from;
}

int parsePath(String path) => node2path(str2node(path[0]), str2node(path[1]));

int countPath(String input) {
  Set<int> visited = new Set.from([0]);
  Set<int> stop = new Set();
  if(input != "") {
    stop = new Set.from(input.split(" ").map(parsePath));
  }
  return count(0, 0, visited, stop);
}

int count(int x, int y, Set visited, Set stop) {
  if(x == WIDTH - 1 && y == HEIGHT - 1) return 1;
  int sum = 0;

  for(var i = 0; i < 4; i++) {
    int nx = x + xs[i];
    int ny = y + ys[i];
    if(0 <= nx && 0 <= ny && nx < WIDTH && ny < HEIGHT) {
      int curNode = pos2node(x, y);
      int nextNode = pos2node(nx, ny);
      int path = node2path(curNode, nextNode);

      if(!visited.contains(nextNode) && !stop.contains(path)) {
        visited.add(nextNode);
        sum += count(nx, ny, visited, stop);
        visited.remove(nextNode);
      }
    }
  }
  return sum;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0