给出了两组测试数据
读者可自行测试
- 思路
m场见面会
i∈[1,m-1]
验证在i的情况下,着色是否成功
#coding=utf-8
#author='HL'
class Solution():
def __init__(self,mat):
self.mat = mat
self.Color = [None]*len(mat)
'''
判断当前点与周围的点是否同色
如果存在同色的
着色失败,返回False
否则,返回True
'''
def Judge(self,number):
for i in range(len(self.mat[number])):
if self.mat[number][i]==1:
if self.Color[i]==self.Color[number]:
return False
return True
'''
step为当前的第i个同学
如果step>=同学个数,返回:正确~
否则:
枚举color_num对当前点进行着色
判断是否成立:如果成立递归即可--直至True
如果失败,返回Fasle
'''
def dfs(self,step,color_num):
if step>=len(self.mat):
return True
else:
for i in range(color_num):
self.Color[step] = i
if self.Judge(step):
if self.dfs(step+1,color_num):
return True
self.Color[step] = None
return False
def solve(self,m):
for i in range(1,m):
if self.dfs(0,i):
return i
return m
test = [[0, 1, 1, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 0, 1, 1, 1],
[0, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 1, 1, 1,0]]
mat = [[0, 1, 1, 1, 0],
[1, 0, 1, 1, 1],
[1, 1, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0]]
zz = Solution(test)
print zz.solve(8)
print zz.Color