我想做的是计算矩阵中与1相邻的1的数量,然后当我计算某个[x][y]时,我计算相邻的数量,并将它们保存在一个名为matrix_的相同矩阵中
现在我面临的问题是,当if循环将邻居识别为1时,它应该计算邻居的数量,然后将其放入矩阵中,但当我在函数中调用它以比较下一个邻居时,计数在主循环中没有得到更新
def compare(x, y, count, Matrix, rows, columns):
while x >= 0 and y >= 0 and x <= (int(rows) - 1) and y <= (int(columns) - 1):
if Matrix[x][y] == 1:
count += 1
break
break
return count
def main():
String = input("Enter the example")
_list = String.split(" ")
print(_list)
rows = _list[0]
columns = _list[1]
Matrix = [[0 for x in range(int(columns))] for y in range(int(rows))]
z = 2
for x in range(0, int(rows)):
for y in range(0, int(columns)):
Matrix[x][y] = int(_list[z])
z += 1
Matrix_qualityies = [[0 for x in range(int(columns))] for y in range(int(rows))]
for x in range(0, int(rows)):
for y in range(0, int(columns)):
count = 0
if Matrix[x][y] == 0:
Matrix_qualityies[x][y] = 0
if Matrix[x][y] == 1:
if x >= 1:
compare(x - 1, y, count, Matrix, rows, columns)
if x >= 1 and y >= 1:
compare(x - 1, y - 1, count, Matrix, rows, columns)
if x >= 1 and y <= (int(columns) - 1):
compare(x - 1, y + 1, count, Matrix, rows, columns)
if x <= (int(rows) - 1):
compare(x + 1, y, count, Matrix, rows, columns)
if x <= (int(rows) - 1) and y >= 1:
compare(x + 1, y - 1, count, Matrix, rows, columns)
if x <= (int(rows) - 1) and y <= (int(columns) - 1):
compare(x + 1, y + 1, count, Matrix, rows, columns)
if y >= 1:
compare(x, y - 1, count, Matrix, rows, columns)
if y <= (int(columns) - 1):
compare(x, y + 1, count, Matrix, rows, columns)
Matrix_qualityies[x][y] = count
print(Matrix)
print(Matrix_qualityies)
main()
输入是2910101101001
通过将邻居提取到辅助函数,您可能可以简化邻居的比较和积累:
也许是这样的
输出示例:
相关问题 更多 >
编程相关推荐