【剑指offer】面试题28的习题:正方体,八皇后

test1 的判定函数:

'''
	@ sum(1,2,3,4) = sum(5,6,7,8) and 
	@ sum(1,2,5,6) = sum(3,4,7,8) and
	@ sum(1,3,5,7) = sum(2,4,6,8)
	@ used for test 1
'''
def sumEqual(data):
	eq1 = sum(data[0:4]) == sum(data[4:8])

	eq2 = sum(data[i << 1] for i in range(4)) == \
		  sum(data[i << 1 | 1] for i in range(4))

	eq3 = sum(data[0:2]) + sum(data[4:6]) == \
		  sum(data[2:4]) + sum(data[6:8])

	return eq1 and eq2 and eq3

test 2 的判定函数:

'''
	@ for square matrix, the slop is +1 or -1, means
	@ abs(p.x - q.x) == abs(p.y - q.y)
	@ for data[], we make index i stand for row(coordinate x) i, and 
	@ data[i] stand for col(coordinate y) data[i], so the conflict 
	@ condition is: abs(i - j) == (data[i] - data[j])
	@ used for test 2
'''
def NotConflict(data):
	for i in range(len(data) - 1):
		for j in range(i + 1, len(data)):
			if abs(i - j) == abs(data[i] - data[j]):
				return False
	return True

主体:

cnt = 0 

'''
	@ get all the permutition of data and print ones that s.t. cf,
'''
def permutition(data, start, cf):
	if len( data ) <= 1:
		return 
	if cf(data):
		print data
		global cnt;
		cnt += 1
	for i in range(start, len( data ) - 1):
		for j in range( i + 1, len( data )):
			data[i], data[j] = data[j], data[i]
			permutition(data, i + 1, cf)
			data[i], data[j] = data[j], data[i]


if __name__ == '__main__':
	data = [0,1,2,3,4,5,6,7,8]
	permutition(data, 0, cf = NotConflict)
	print cnt


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值