Word Search

Source

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.

Have you met this question in a real interview? Yes
Example
Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Java

public class Solution {
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    public boolean exist(char[][] board, String word) {
        if(board==null || board.length==0 || board[0].length==0) return false;

        int m = board.length;
        int 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, i, j, word, 0, visited)){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(char[][] board, int x, int y, String word, int index, boolean[][] visited){
        if(x<0 || x>board.length-1 || y<0 || y>board[0].length-1){
            return false;
        }
        if(visited[x][y] || board[x][y]!=word.charAt(index)){
            return false;
        }
        if(index==word.length()-1){
            return true;
        }
        visited[x][y] = true;
        //search top
        if(dfs(board, x-1, y, word, index+1, visited)) return true;
        //search bottom
        if(dfs(board, x+1, y, word, index+1, visited)) return true;
        //search left
        if(dfs(board, x, y-1, word, index+1, visited)) return true;
        //search right
        if(dfs(board, x, y+1, word, index+1, visited)) return true;

        visited[x][y]=false;
        return false;
    }
}