【試題描述】
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。(PS:數組的不一定是n*n的矩陣)
【試題來源】未知
【試題分析】
總體思路就是使用遞歸+二分查找的方法,具體過程如下所示:
設二分查找的中間點爲(m_x,m_y),其中
m_x = (s_x +e_x) / 2
m_y = (s_y +e_y) / 2
【源代碼Python】
#!/usr/bin/env python
def find_matrix(mat, s_x, s_y, e_x, e_y, key):
"""
mat:傳入的矩陣
(s_x, s_y):矩陣左上角座標值
(e_x, e_y):矩陣右下角座標值
"""
#明確key不在矩陣中的時候
if mat[s_x][s_y] > key or mat[e_x][e_y] < key:
return False
#當矩陣規模爲1*1的時候
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()
【參考資料】
http://topic.csdn.net/u/20111214/10/d09797c3-d1ce-4249-b1e5-8b693b4c85f8.html
http://justjavac.iteye.com/blog/1310178
http://nubnub.blog.163.com/blog/static/169186347201192411857362/