75 leetcode - Word Search

回溯法

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Word Search.
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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
'''
class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        word_len = len(word)
        if word_len == 0:
            return True

        row_len = len(board)
        if row_len == 0:
            return False

        col_len = len(board[0])

        if col_len == 0:
            return False

        if col_len * row_len < word_len:
            return False
        flag = [[False] * col_len for i in range(row_len)]
        for row,s in enumerate(board):
            for col,val in enumerate(s):
                if val == word[0]:
                    flag[row][col] = True
                    if self._exist(board,row,col,row_len,col_len,word,1,word_len,flag) == True:
                        return True
                    flag[row][col] = False

        return False

    def _exist(self,board,row,col,row_len,col_len,word,index,word_len,flag):
        '''最直观版本...也可以改成for循环,注意不要越界'''
        if index >= word_len:
            return True
        if col > 0 and flag[row][col - 1] == False and board[row][col - 1] == word[index]:
            flag[row][col - 1] = True
            if self._exist(board,row,col - 1,row_len,col_len,word,index + 1 ,word_len,flag) == True:
                return True
            flag[row][col - 1] = False

        if col < (col_len - 1) and flag[row][col + 1] == False and board[row][col + 1] == word[index]:
            flag[row][col + 1] = True
            if self._exist(board,row,col + 1,row_len,col_len,word,index + 1 ,word_len,flag) == True:
                return True
            flag[row][col + 1] = False 

        if row > 0 and flag[row - 1][col] == False and board[row - 1][col] == word[index]:
            flag[row - 1][col] = True
            if self._exist(board,row - 1,col,row_len,col_len,word,index + 1 ,word_len,flag) == True:
                return True
            flag[row - 1][col] = False

        if row < (row_len - 1) and flag[row + 1][col] == False and board[row + 1][col] == word[index]:
            flag[row + 1][col] = True
            if self._exist(board,row + 1,col,row_len,col_len,word,index + 1 ,word_len,flag) == True:
                return True
            flag[row + 1][col] = False

        return False

if __name__ == "__main__":
    s = Solution()
    a = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]
    print s.exist(a,'ABCCED')
    print s.exist(a,'SEE')
    print s.exist(a,'ABCB')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值