Home > AI > Data Structure >

(HackerRank) The Grid Search

Solution: Python

def gridSearch(G, P):
    H, W = len(G), len(G[0])
    h, w = len(P), len(P[0])
    
    for i in range(H):
        start_idx = G[i].find(P[0])
        
        if start_idx != -1:
            while start_idx != -1:
                # iterate the following rows
                j = 1
                while j < h and G[i+j][start_idx:start_idx+w] == P[j]:
                    j += 1
                    
                if j == h:
                    return "YES"
                
                start_idx = G[i].find(P[0], start_idx+1) # iterate the current row in case there are two patterns in the same row
    return "NO"

Leave a Reply