Leetcode 79. Word Search搜单词,递归深度搜索python3初试

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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

题目链接:https://leetcode.com/problems/word-search/

思路:递归深度搜索

class Solution {
    public:
    bool find(vector<vector<char>>board,string word,int c,int x,int y)
    {
        if(c>word.length()-1)
        {
            return true;
        }
        else if(x<0||y<0||x>board.size()-1||y>board[0].size()-1||board[x][y]!=word[c])//x代表行号,y代表列号,别弄反了,不然会runtime error
        {
            return false;
        }
        else
        {
            board[x][y]='#';
            if(find(board,word,c+1,x-1,y)||find(board,word,c+1,x+1,y)||find(board,word,c+1,x,y+1)||find(board,word,c+1,x,y-1))
                return true;
        }
        return false;
    }
        
    	 bool exist(vector<vector<char> > &board, string word) {
    		 int m=board.size();
             if(m<1)
                 return false;
    		 int n=board[0].size();
             int c=0;
             for(int x=0;x<m;x++)
             {
                 for(int y=0;y<n;y++)
                 {
                     if(find(board,word,c,x,y))
                     {
                         return true;
                     }
                 }
             }
            return false;
        }
    };

学了python3,我也想学以致用,用同样的思路写了份python代码,但是很不成功,通过了78/87,我也很奇怪,没有找出两份代码执行结果究竟有什么不同,先把代码放在这里

class Solution:
    def find(self,board,word,c,x,y):
        if c>len(word)-1:
            return True
        elif x<0 or y<0 or x>len(board)-1 or y>len(board[0])-1 or board[x][y]!=word[c]:
            return False
        else:
            board[x][y]='#'
            if self.find(board,word,c+1,x-1,y) or self.find(board,word,c+1,x+1,y) or self.find(board,word,c+1,x,y+1) or self.find(board,word,c+1,x,y-1):
                return True
        return False

    
    def exist(self,board,word):
        m,n=len(board),len(board[0])
        c=0
        for i in range(m):
            for j in range(n):
                if self.find(board,word,c,i,j):
                     return True
        return False

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86678169