Word Search Leetcode


#1

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.

#2

The below code uses DFS. It calls dfs when the first character is a match.

var xa = []int{0, 0, 1, -1}
var ya = []int{1, -1, 0, 0}

func exist(board [][]byte, word string) bool {
    seen := createSeen(len(board), len(board[0]))
    for i:=0;i<len(board);i++{
        for j:=0;j<len(board[i]);j++{
            if board[i][j]==word[0]{
                 // create seen only if there's a match, avoids unnecessary memory allocation.
                if dfs(board, word, 0, i, j, seen){
                    return true
                 }
            }
           
        }
    }
    return false
}

func createSeen(m, n int)[][]bool{
    seen := make([][]bool, m)
    for i := range seen {
        seen[i] = make([]bool, n)
    }

    return seen
}

func dfs(board [][]byte, word string, c int, i, j int,seen [][]bool) bool {
    if c==len(word){
        return true
    }
    
    if (i<0 || i==len(board) || j<0 || j==len(board[0]) || board[i][j]!=word[c] || seen[i][j]){
        return false
    }
    
    seen[i][j] = true
    var flag bool
    for x:=0;x<len(xa);x++{
         flag = flag || dfs(board, word, c+1, i+xa[x], j+ya[x], seen)
    }
    seen[i][j] = false
    return flag
}

#3

DFS approach in Java,

class Solution {
    public boolean exist(char[][] board, String word) {
      if(board==null || board.length==0 || word==null || word.length()==0) return false;
        int m =  board.length;
        int n =  board[0].length;
        if(word.length() > m*n) 
            return false;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]==word.charAt(0)){
                    if(dfs(board, word, i, j, 0, new boolean[board.length][board[0].length]))
                        return true;
                }
            }
        }
        
        return false;
    }
    int[][] cords = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    private boolean dfs(char[][] board, String word, int i, int j, int pos, boolean[][] visited){
        if(pos==word.length()) return true;
        if(i<0 || j<0 || i>=board.length || j>=board[0].length) return false;
        if(visited[i][j] || board[i][j]!=word.charAt(pos)) return false;
        visited[i][j] = true;
        boolean found = false;
        for(int[] cord : cords){
            found = found || dfs(board, word, i+cord[0], j+cord[1], pos+1, visited);
        }
        visited[i][j] = false;
        return found;
    }

}