• leetcode79


    class Solution {
        public boolean exist(char[][] board, String word) {
            for(int i=0; i<board.length; i++) {
                for(int j=0; j<board[0].length; j++) {
                    if(exist(board, i, j, word, 0))
                        return true;
                }
            }
            return false;
        }
        
        public boolean exist(char[][] board, int x, int y, String word, int index) {
            if(index == word.length()) return true;
            if(x < 0 || y<0 || x>=board.length || y>=board[0].length || board[x][y] != word.charAt(index))
                return false;
                
            board[x][y] ^= 128;
            boolean exist = exist(board, x-1, y, word, index+1) || 
                            exist(board, x+1, y, word, index+1) ||
                            exist(board, x, y-1, word, index+1) ||
                            exist(board, x, y+1, word, index+1) ;
            board[x][y] ^= 128;
            return exist;
        }
    }

    补充一个python的实现:

     1 class Solution:
     2     def dfs(self,board,word,index,rows,coloums,visited,i,j):
     3         if index >= len(word):
     4             return True
     5         if i >= rows or i < 0 or j >= coloums or j < 0 or visited[i][j] == 1 or board[i][j] != word[index]:
     6             return False
     7         visited[i][j] = 1
     8         result = self.dfs(board,word,index+1,rows,coloums,visited,i+1,j) or self.dfs(board,word,index+1,rows,coloums,visited,i-1,j) or self.dfs(board,word,index+1,rows,coloums,visited,i,j+1) or self.dfs(board,word,index+1,rows,coloums,visited,i,j-1)
     9 
    10         visited[i][j] = 0
    11 
    12         return result
    13 
    14     def exist(self, board: 'List[List[str]]', word: 'str') -> 'bool':
    15         rows = len(board)
    16         coloums = len(board[0])
    17         visited = [[0 for a in range(coloums)] for b in range(rows)]
    18         for i in range(rows):
    19             for j in range(coloums):
    20                 if self.dfs(board,word,0,rows,coloums,visited,i,j):
    21                     return True
    22         return False
  • 相关阅读:
    gitlab安装配置
    jenkins忘记admin密码的处理方法
    jenkins权限管理插件role-based(二)
    jenkins安装部署(一)
    ERROR 1129 (HY000): Host '192.168.7.210' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'
    nginx重试机制proxy_next_upstream
    nginx配置ssi
    python实现查找指定文件
    python 调用系统命令
    Android 调用资源字符串的几种方法
  • 原文地址:https://www.cnblogs.com/asenyang/p/9791034.html
Copyright © 2020-2023  润新知