示例#1
0
文件: bt.py 项目: nbari/my-sandbox
def solve(start, sum_rows, sum_cols, M, line):

    check = verify_matrix(M, sum_rows, sum_cols)

    """
    backtracking
    """

    if check[0] == False:  # reject
        return

    if check[1]:  # accept
        print 'Yes'
        quit()
    for i in check[2]:
        if i >= M.shape[0] - line:
            return

    # first
    line += 1
    if line >= M.shape[0]:
        return

    possibilities = [i for i in xrange(len(check[2])) if check[2][i] > 0]

    if len(possibilities) < sum_rows[line]:
        return

    N = M.copy()
    N[line] = numpy.zeros(M.shape[1])
    for i in xrange(sum_rows[line]):
        N[line][possibilities[i]] = 1

    solve(start, sum_rows, sum_cols, N, line)

    O = N

    possibilities = [i for i in xrange(len(check[2])) if check[2][i] > 0]

    O[line] = numpy.zeros(M.shape[1])
    for p in itertools.combinations(possibilities, sum_rows[line]):

        O[line] = numpy.zeros(M.shape[1])
        for i in p:
            O[line][i] = 1

        solve(start, sum_rows, sum_cols, O, line)
示例#2
0
文件: bt.py 项目: nbari/my-sandbox
def main(data):
    sum_rows = [int(x) for x in data[1].split()]
    sum_cols = [int(y) for y in data[2].split()]
    M = numpy.zeros(shape=(len(sum_rows), len(sum_cols)))
    solve(time.time(), sum_rows, sum_cols, M, -1)
    print 'No'