1. 程式人生 > >Leetcode 79 Word Search

Leetcode 79 Word Search

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.

class Solution {
    public boolean exist(char[][] board, String word) {
        
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[i].length; j++){
                if(isExist(board,word,i,j,0)) return true;
            }
        }
        
        return false;
    }
    
    public boolean isExist(char[][] board,String word,int x,int y,int d){
        if(d == word.length()) return true;
        if(x < 0 || x == board.length || y < 0 || y == board[0].length) return false;
        if(board[x][y] != word.charAt(d)) return false;
        
        char temp = board[x][y];
        board[x][y] = '0';
        boolean res = isExist(board,word,x-1,y,d+1) ||
            isExist(board,word,x,y-1,d+1) ||
            isExist(board,word,x,y+1,d+1) ||
            isExist(board,word,x+1,y,d+1);
        board[x][y] = temp;
        return res;                    
    }
}