知恵袋の立方体の色の塗り分け問題をPythonで解いてみました。(^_^;
立方体の各面に、隣り合った面の色は異なるように、色を塗りたい。回転させて一致するものは同じとみなす。
この場合の、異なる6色、5色、4色を使って塗るときは何通りありますか?
立方体の面に次のようにA〜Fと名前を付けました。また、色の名前をa〜fとしました。(^_^;
+-----+ |\ C /| | +-+ | |E|A|F| | +-+ | |/ D \| +-----+ (B)裏面
● CubicColoring1.py
# coding: UTF-8 # CubicColoring1.py import itertools from time import time DB = [] # 発見したパターンの記録用 # 回転させて一致する塗り方のパターンか調べる def isSamePat(p): A,B,C,D,E,F = p S = [] T = [(A,B,C,D,E,F),(A,B,E,F,D,C),(A,B,D,C,F,E),(A,B,F,E,C,D)] for t in T: s = "%s%s|%s%s|%s%s|"%t*2 S.append(s+s[::-1]) for d in DB: for s in S: if d in s: return True DB.append("%s%s|%s%s|%s%s"%p) return False def main(): tm=time() # Timer Start P = 'abcdef' # 色 N = [6,5,4] # 色数 c = [0]*len(N) for n in N: DB = [] for p in itertools.product(P[:n],repeat=6): A,B,C,D,E,F = p # 同じ色が隣接したらスキップ if A==C or A==D or A==E or A==F: continue if B==C or B==D or B==E or B==F: continue if C==E or C==F or D==E or D==F: continue if len(set(p))!=n: continue # 色の数をチェック if isSamePat(p): continue # 回転させて同じパターンならスキップ # チェックを潜り抜けたものだけをカウント c[N.index(n)]+=1 for i in range(len(N)): print("(%d) %d"%(i+1,c[i])) print("Runtime : %.3f [sec]"%(time()-tm)) # Timer Stop & Disp if __name__ == '__main__': main()
●実行結果
(1) 30 (2) 15 (3) 6 Runtime : 0.080 [sec]
※参考URL
http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q13158083928
●立方体の塗り分け
●知恵袋の正八面体の色の塗り分け問題をPythonで解いてみた。
●知恵袋の正八面体の色の塗り分け問題をPythonで解いてみた。(2)