Leetcode: Word Search

来源:互联网 发布:手机java游戏模拟器 编辑:程序博客网 时间:2024/04/26 07:21

Get idea from Code Ganker′s (CSDN) solution, also from this solution


Question

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
Hide Tags Array Backtracking


Analysis

Treat each letter as a node in graph and its four cells as its neighbors. Use DFS to find path. Since the same cell may not be used more than once, we can create an array named visited to store info whether this cell have been visited.

Step:
1. look for all cells that can be the first one of word
2. for each cell, do DFS. Note that we need to set it be False at the end.

Complexity:
for init point, we look for all nodes, which takes O(m*n). For each DFS, it is O(E+V) = O(m*n+4m*n) = O(m*n). Thus it takes O(m2n2) totally.


Solution

class Solution:    # @param {character[][]} board    # @param {string} word    # @return {boolean}    def exist(self, board, word):        if len(board)==0 or len(word)==0:            return False        self.move = [[0,0,1,-1],[1,-1,0,0]]                visited = [ [False]*len(board[0]) for dummy_i in range(len(board)) ]        for i in range(len(board)):            for j in range(len(board[0])):                if self.search(board,word,0,i,j,visited):                    return True        return False    def search(self,board,word,index,i,j,visited):        if index==len(word):            return True        if i<0 or j<0 or i>=len(board) or j>=len(board[0])              or word[index]!=board[i][j] or visited[i][j]==True:            return False        result = False        visited[i][j] = True        for direct in range(4):            result = result or self.search(board, word, index+1, i+self.move[0][direct],                       j+self.move[1][direct],visited)        visited[i][j] = False        return result

Take-home message

The tricks here are:
1. to make logic clear, put all (or some) checks in helper function. In help function(search), it checks whether the indexes are in the board, whether it is visited …….
2. to create move array for moving, not need to list all directions one by one self.move = [[0,0,1,-1],[1,-1,0,0]]


0 0
原创粉丝点击