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.

For example,
Given board=

[ 
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word ="ABCCED", -> returnstrue,

word ="SEE", -> returnstrue,

word ="ABCB", -> returnsfalse.

思路:绕啊绕

public class Solution {
    public boolean exist(char[][] board, String word) {
        boolean res = false;
        for (int i=0;i<board.length;i++){
            for (int j=0;j<board[0].length;j++){
                if (searchOne(board,word,i,j,0))
                    res = true;
            }
        }
        return res;
    }

    public boolean searchOne(char[][] board, String word, int i, int j, int pos){
        if (i<0||j<0||i>board.length-1||j>board[0].length-1){
            return false;
        }

        if (board[i][j] == word.charAt(pos)){
            if (word.length()==pos+1){
                return true;
            }
            char temp = board[i][j];
            board[i][j] = '*';
            if (searchOne(board, word, i+1, j, pos+1))  return true;
            if (searchOne(board, word, i-1, j, pos+1))  return true;
            if (searchOne(board, word, i, j+1, pos+1))  return true;
            if (searchOne(board, word, i, j-1, pos+1))  return true;
            board[i][j] = temp;
        }

        return false;
    }
}

results matching ""

    No results matching ""