[leetCode] Word Search (new start. Let's go this)

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 = 

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

word = "ABCB", -> returns false.

public class Solution {
    public boolean exist(char[][] board, String word) {

        boolean res = false;
        boolean[][] flag = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    res = existHelper(board, flag, word, 0, i, j);
                    if (res == true) return res;
                }
            }
        }
        return res;
    }

    private boolean existHelper(char[][] board, boolean[][] flag, String word, int index, int x, int y) {

        flag[x][y] = true;
        if (index == word.length() - 1) return true;
    
        boolean f = false;
        if (x - 1 >= 0 && flag[x-1][y] == false && board[x-1][y] == word.charAt(index+1)) {
            f |= existHelper(board, flag, word, index+1, x-1, y);
        }
        if (x + 1 < board.length && flag[x+1][y] == false && board[x+1][y] == word.charAt(index+1)) {
            f |= existHelper(board, flag, word, index+1, x+1, y);
        }
        if (y - 1 >= 0 && flag[x][y-1] == false && board[x][y-1] == word.charAt(index+1)) {
            f |= existHelper(board, flag, word, index+1, x, y-1);
        }
        if (y + 1 < board[0].length  && flag[x][y+1] == false && board[x][y+1] == word.charAt(index+1)) {
            f |= existHelper(board, flag, word, index+1, x, y+1);
        }
        if (f == false) flag[x][y] = false;
        return f;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章