Advertisement
alisadafi

Matrix-Search-D&C

Nov 9th, 2023 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. from typing import List
  2.  
  3. def find(X: List[List[int]], k: int, top_left_i: int, top_left_j: int, bottom_right_i: int, bottom_right_j: int):
  4.     m_i = (top_left_i + bottom_right_i) // 2
  5.     m_j = (top_left_j + bottom_right_j) // 2
  6.  
  7.     if X[m_i][m_j] == k:
  8.         return (m_i, m_j)
  9.  
  10.     if top_left_i == bottom_right_i and top_left_j == bottom_right_j:
  11.         return (-1, -1)  # not found
  12.  
  13.     if top_left_i > bottom_right_i or top_left_j > bottom_right_j:
  14.         return (-1, -1)  # not found
  15.  
  16.     if X[m_i][m_j] > k:
  17.         pos = find(X, k, top_left_i, top_left_j, m_i - 1, m_j - 1)
  18.         if pos != (-1, -1):
  19.             return pos
  20.  
  21.         pos = find(X, k, m_i, top_left_j, bottom_right_i, m_j - 1)
  22.         if pos != (-1, -1):
  23.             return pos
  24.  
  25.         pos = find(X, k, top_left_i, m_j, m_i - 1, bottom_right_j)
  26.         if pos != (-1, -1):
  27.             return pos
  28.  
  29.     else:
  30.         pos = find(X, k, m_i + 1, m_j + 1, bottom_right_i, bottom_right_j)
  31.         if pos != (-1, -1):
  32.             return pos
  33.  
  34.         pos = find(X, k, m_i + 1, top_left_j, bottom_right_i, m_j)
  35.         if pos != (-1, -1):
  36.             return pos
  37.  
  38.         pos = find(X, k, top_left_i, m_j + 1, m_i, bottom_right_j)
  39.         if pos != (-1, -1):
  40.             return pos
  41.  
  42.     return (-1, -1)  # not found
  43.  
  44.  
  45.  
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement