79. 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.

public class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length,n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for(int i=0;i<m;i++)
          for(int j=0;j<n;j++)
          {
              if(DFS(board,word,0,i,j,visited))
                return true;
          }
        return false;
    }
    
    public boolean DFS(char[][] board,String word,int index,int i,int j,boolean[][] visited)
    {
        if(index == word.length())
          return true;
        if(i<0||j<0||i>=board.length||j>=board[0].length)
          return false;
        if(visited[i][j])
          return false;
        if(board[i][j] != word.charAt(index))
          return false;
        int[][] direction = {{-1,0},{1,0},{0,1},{0,-1}};
        for(int k=0;k<direction.length;k++)
        {
            int ii = i + direction[k][0];
            int jj = j + direction[k][1];
            visited[i][j] = true;
            if(DFS(board,word,index+1,ii,jj,visited))
               return true;
        }
        visited[i][j] = false;
        return false;
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容