Leetcode-Word Search(Java)

Question:

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.

Thinking:

I assume it’s graph and do dfs in this 2d array. Start from every point and search the result until find the solution or failure. In this process, we need to record the visitied set. In my solution, I used the hashset. But in more efficient way, we can use bit manipulate to mask the visited element.

Solution:

My solution(use HashSet):

public boolean exist(char[][] board, String word) {
    int m = board.length;
    if (m == 0)    return false;
    int n = board[0].length;
    Set<Integer> record = new HashSet<Integer>();
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            if (backtracking(board, word, 0, i, j, record))    return true;
    return false;
}

private boolean backtracking(char[][] board, String word, int index, int i, int j, Set<Integer> record) {
    if (board[i][j] == word.charAt(index) && !record.contains(i*board[0].length+j)){
        if (index == word.length()-1)    return true;
        boolean res = false;
        record.add(i*board[0].length+j);
        if (i-1>=0)    res |= backtracking(board, word, index+1, i-1, j, record);
        if (!res && i+1<board.length) res |= backtracking(board, word, index+1, i+1, j, record);
        if (!res && j-1>=0)    res |= backtracking(board, word, index+1, i, j-1, record);
        if (!res && j+1<board[0].length) res |= backtracking(board, word, index+1, i, j+1, record);
        record.remove(i*board[0].length+j);
        return res;
    }
    return false;
}

use the mask:

public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y<board.length; y++) {
        for (int x=0; x<board[y].length; x++) {
            if (exist(board, y, x, w, 0)) return true;
        }
    }
    return false;
}

private boolean exist(char[][] board, int y, int x, char[] word, int i) {
    if (i == word.length) return true;
    if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
    if (board[y][x] != word[i]) return false;
        board[y][x] ^= 256;
    boolean exist = exist(board, y, x+1, word, i+1)
    || exist(board, y, x-1, word, i+1)
    || exist(board, y+1, x, word, i+1)
    || exist(board, y-1, x, word, i+1);
    board[y][x] ^= 256;
    return exist;
}