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.

Have you met this question in a real interview? Yes
Example
Given board =

[
"ABCE",
"SFCS",
"ADEE"
]

分析

重点是要使用递归来简化逻辑,难点在于如果避免找一个元素的临元素时,不再找回来这个元素。比如我们找到(i,j),在查找(i+1,j)的时候不能再查找(i,j)。代码中采用的是先把(i,j)修改为一个不可能出现的元素,但是这次搜索可能是错的,所以在返回递归的时候需要把它再修改回来。

代码

public class Solution {
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    public boolean exist(char[][] board, String word) {
        // write your code here
        for(int i=0;i=board.length||j>=board[0].length){
            return false;
        }
        if(word.charAt(index)==board[i][j]){
            board[i][j]=' ';
            boolean b=isValidate(i-1,j,board,word,index+1)||isValidate(i,j-1,board,word,index+1)||isValidate(i+1,j,board,word,index+1)||isValidate(i,j+1,board,word,index+1);
            board[i][j]=word.charAt(index);
            return b;
        }
        return false;
    }
}

你可能感兴趣的:(Word Search(单词搜索))