Python 矩阵相邻

半腔热情 提交于 2020-01-21 03:17:00

题目描述:
一个矩阵,5*5,取相邻(二个成员有一个边是相同的)的6个,输入一个6个成员列表,判断是否满足?
矩阵成员如下:
[[1,2,3,4,5],
[11,12,13,14,15],
[21,22,23,24,25],
[31,32,33,34,35],
[41,42,43,44,45]].
输入描述:
包含6个矩阵成员数组,如:1,2,3,4,5,11以一个空格分隔,支持多行
1,2,3,4,5,11
1,2,11,14,25,15

输出描述:
满足输出1,否则输出0,每一行输入一个输出
1
0

def label(df, num):
    result = []
    found = False
    for i in range(len(df)):
        for j in range(len(df[i])):
            if num == df[i][j] and not found:
                found = True
                result.append(i)
                result.append(j)
    if not found:
        return False
    else:
        return result

def nearby(i1, j1, i2, j2):
    if abs(i2 - i1) + abs(j2 - j1) <= 1:
        return True
    else:
        return False

def continuous(df, alist):
    result = [False] * len(alist)
    for i in alist:
        if label(df, i) != False:
            for j in alist:
                if label(df, j) != False:
                    if i != j and nearby(label(df, i)[0], label(df, i)[1], label(df, j)[0], label(df, j)[1]):
                        result[alist.index(i)] = True
            # if not result[alist.index(i)]:
            #     print (str(i) + "与其他数字不相邻!")
        else:
            # print("%d不在矩阵中!" %(i))
            break

    return print((int(result == ([True] * len(alist)))))

def dftolist(df, inputs):
    for alist in inputs:
        continuous(df, alist)

if __name__ == "__main__":
    df = [[1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45]]
    inputs = [[1, 2, 3, 4, 12, 14],[1, 2, 3, 4, 12, 24],[1, 2, 3, 4, 14, 24],[1, 2, 3, 4, 12, 15]]
    dftolist(df, inputs)

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!