欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

79. Word Search

程序员文章站 2022-07-14 17:31:09
...

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;
    }
    
}