首页 > 解决方案 > 在矩阵python中查找矩阵的中间索引

问题描述

我正在尝试在矩阵中找到矩阵的开始和停止

例如有一个 W 和 B 的矩阵,B 是整个矩阵内的一个正方形:

5 6
WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW

我想得到中间:

BBB
BBB
BBB

这应该输出我:

2 4

因为矩阵在另一个矩阵中

我的想法是取正方形并使中间的 B1 然后在整个矩阵中索引它。

我已经尝试了我制作的以下代码。

def middle(m):
    # for getting the middle of BlackPart
    n = len(m)//2
    n1 = len(m[n])//2
    m[n][n1] = "B1"
    return m

def find(matrix, list1):
    # for getting B list
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == "B":
                list1.append("B")
                return list1

def q2():
    # for getting matrix
    nope = input("").split(" ")
    counter1 = 0
    m = []
    while counter1 < int(nope[0]):
        a = input("")
        m.append(list(a))
        counter1 += 1
    # for getting matrix

    # below is for getting a square matrix

    l = []
    find(m, l)
    n = int(len(l) ** (1 / 2))
    counter = 0
    for i in range(len(l) // 3):
        l += [l[counter * n: counter * n + n]]
        counter += 1

    middle(m)
q2()

但它太复杂了,让我感到困惑,然后我最终注意到它是失败的。

请告诉我是否有更简单的方法可以做到这一点。

谢谢

标签: pythonmatrix

解决方案


你去,我想通了:

matrix = """WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW"""
bstart = 0
bend = 0
bfound = False
bposition_x = 0
bposition_y = 0
bstartline = 0
bfoundinlines = []
matrix = matrix.split("\n")
for linenum, line in enumerate(matrix):
    bfound = False
    for index, x in enumerate(line):
        if x == "B" and bfound == False:
            bstart = index
            bfound = True
            bfoundinlines.append(linenum)
        elif x == "W" and bfound == True:
            bend = index - 1
    bstartline += 1

bposition_x = int((bstart + bend)/2 + 1)
bposition_y = int(round(len(bfoundinlines)/2)) # 1 already added (counting from 1)
if len(bfoundinlines) == 1: bposition_y = 2 #python rounds 0.5 to 0
print("from top:",bposition_y,"from left",bposition_x)

推荐阅读