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