Coding Challenge 测试用例和运行时失败

问题描述

给定一个 m × n 的正整数矩阵 inmatrix,根据以下逻辑打印一个整数 outnum:

Identify all possible sets in inmatrix that contain at least four consecutive elements of the same value val,either horizontally,vertically,or diagonally
If only one set of consecutive elements is identified,store the value val in outnum
If more than one set of consecutive elements is identified,find the smallest value and store it in outnum
If no set of four consecutive elements of the same value is identified either horizontally,or diagonally,print -1

假设:

m and n will be greater than 3

输入格式:

第一行将包含矩阵的行数 m

接下来的 m 行将包含 inmatrix 的元素。每行将有 n 个元素,以空格分隔。

从标准输入流中读取输入。

输出格式:

将 outnum 打印到标准输出流。

样本输入

5 0 1 6 8 8 9 5 6 1 6 8 9 6 5 6 1 1 9 1 6 6 1 1 9 6 3 3 3 3 9

样本输出

1

以下元素至少连续出现四次:第 5 行中的元素 3 水平。元素 1 从第一行的第 2 列对角线开始。元素 6 从第二行的第 4 列对角线开始。元素 9 垂直位于第 6 列。由于元素 1 是已识别的四组连续值中的最小值,因此输出为 1

输入:

5

0 1 6 8 6 0 5 5 2 1 8 2 6 5 6 1 1 9 1 5 6 1 4 0 3 7 3 3 4 0

输出

-1

这里不存在水平、垂直或对角线上具有相同值的四个连续元素的集合。因此输出为 -1。

我已经用 Python 编写了以下代码。它通过了 7 个测试用例,但失败了一个,同时运行时间超过了另外两个。我可以修复反向对角线的东西,但我认为我的实现是错误的,因为我的时间限制超过了。有什么想法吗?

from array import *
p = int(input())
if p<3:
    print("-1")
    exit(0)
rows,cols = p+1,p
arr = []

for i in range(p):
    y = [int(i) for i in input().split(' ')]
    arr.append(y)
lst = array('Q')
for i in arr:
    arr2 = array('Q',i)
    for j in range(cols-2):
        if arr2[j] == arr2[j+1] == arr2[j+2] == arr2[j+3]:
            lst.append(arr2[j])

for i in range(rows):
    for j in range(cols-3):
        if arr[j][i] == arr[j+1][i] == arr[j+2][i] == arr[j+3][i]:
            lst.append(arr[j][i])

u = []
for k in range(p-2):
    h = []
    for i in range(cols):
        for j in range(rows):
            if i == j-k:
               h.append(arr[i][j])
    u.append(h)
for k in range(p-4):
    h = []
    for i in range(cols):
        for j in range(rows):
            if i-k-1 == j:
               h.append(arr[i][j])
    u.append(h)
for k in range(p-2):
    h = []
    for i in range(cols):
        for j in range(rows):
            if i == p-j-k:
               h.append(arr[i][j])
    u.append(h)
for k in range(p-4):
    h = []
    for i in range(cols):
        for j in range(rows):
            if i-k-1 == p-j:
               h.append(arr[i][j])
    u.append(h)
op = len(u)
for i in range(op):
    opi = len(u[i])
    if opi <=4: o = 1
    else: o = opi-3
    for j in range(o):
        if u[i][j] == u[i][j+1] == u[i][j+2] == u[i][j+3]:
            lst.append(u[i][j])

if len(lst) == 0:
    print("-1")
else:
    print(min(lst))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)