href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第79题--Integer to Roman
题目
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.
思路 这道题可以用递归函数来解决,注意到,eg从“a” 中判断是否有“aa” ,如果直接递归是返回true的,这不对,要就是说在一次判断中,已判断过的字母不能再判断,所以参数应该还有一个board,记录当前的字母状态,考虑到python是用的引用,传递参数时没有复制,我又不想额外再去复制board,就在函数中记下当前位置的字母,在函数调用结束再改回来的。哈哈!
show me the code
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ row = len(board) col = len(board[0]) num = len(word) def find(r,c,n): if n == num-1 and board[r][c] == word[n]: return True if board[r][c] != word[n] or n == num-1: return False tmp = board[r][c] #save the val board[r][c] = 0 if r < row-1 and find(r 1,c,n 1): return True if r > 0 and find(r-1,c,n 1): return True if c <col-1 and find(r,1 c,n 1): return True if c > 0 and find(r,c-1,n 1): return True board[r][c] = tmp return False for i in range(row): for j in range(col): if find(i,j,0): return True return False