2015年11月17日火曜日

151117

C


Self-avoiding walk(1)

『フカシギの数え方』 おねえさんといっしょ! みんなで数えてみよう!
の動画で有名な問題を解いてみた。
なお、オンライン整数列大辞典の
A007764(http://oeis.org/A007764/list)
に詳しく載っている。

#include <stdio.h>

// startがx, y、goalがw - 1, h - 1
int search(int x, int y, int w, int h, long long used, int depth){
 int cnt = 0;
 if (x < 0 || w <= x || y < 0 || h <= y || (used & (1LL << (x + y * w))) > 0) return 0;
 if (x == w - 1 && y == h - 1) return 1;
 used += 1LL << (x + y * w);
 cnt += search(x + 1, y, w, h, used, depth + 1);
 cnt += search(x - 1, y, w, h, used, depth + 1);
 cnt += search(x, y + 1, w, h, used, depth + 1);
 cnt += search(x, y - 1, w, h, used, depth + 1);
 used -= 1LL << (x + y * w);
 return cnt;
}

int main(void){
 int i;
 long long used;
 for (i = 1; i < 8; i++){
  used = 0LL;
  printf("%d\n", search(0, 0, i, i, used, 1));
 }
 return 0;
}

出力結果
1
2
12
184
8512
1262816
575780564

0 件のコメント:

コメントを投稿

注: コメントを投稿できるのは、このブログのメンバーだけです。