1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
def find_matrix(mat, s_x, s_y, e_x, e_y, key): """ mat:传入的矩阵 (s_x, s_y):矩阵左上角坐标值 (e_x, e_y):矩阵右下角坐标值 """ if mat[s_x][s_y] > key or mat[e_x][e_y] < key: return False
if s_x == e_x and s_y == e_y: if mat[s_x][s_y] == key: print("(%s, %s)" % (s_x, s_y)) return True else: return False
m_x = int((s_x + e_x) / 2) m_y = int((s_y + e_y) / 2) if mat[m_x][m_y] == key: print("(%s, %s)" % (s_x, s_y)) return True elif mat[m_x][m_y] > key: return find_matrix(mat,s_x, s_y, m_x, m_y, key) \ or find_matrix(mat,s_x, m_y + 1, m_x - 1, e_y, key) \ or find_matrix(mat,m_x + 1, s_y, e_x, m_y - 1, key) elif mat[m_x][m_y] < key: return find_matrix(mat,m_x + 1, s_y, e_x, m_y, key) \ or find_matrix(mat,s_x, m_y + 1, m_x, e_y, key) \ or find_matrix(mat,m_x + 1, m_y + 1, e_x, e_y, key)
def main(): matrix = [[1, 2, 3 , 4, 5], [6, 7, 8 , 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]] key = 24 if find_matrix(matrix, 0, 0, len(matrix) - 1, len(matrix[0]) - 1, key): print("Found!") else: print("Not Found!")
if __name__ == '__main__': main()
|