Word Search

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

Given board =

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

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

考察:DFS 递归---回溯

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) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        if (word.length() == 0) {
            return true;
        }
        boolean result = false;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    result = findWord(board, i, j, word, 0);
                    if (result == true) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    private boolean findWord(char[][] board, int i, int j, String word, int start) {
        if (start == word.length()) {
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || 
            board[i][j] != word.charAt(start)) {
            return false;
        }
        board[i][j] = ‘#‘;
        boolean result = findWord(board, i - 1, j, word, start + 1) || 
           findWord(board, i + 1, j , word, start + 1) || 
           findWord(board, i, j - 1, word, start + 1) || 
           findWord(board, i, j + 1, word, start + 1);
        board[i][j] = word.charAt(start);
        return result;
    }
}

 

以上是关于Word Search的主要内容,如果未能解决你的问题,请参考以下文章

刷题79. Word Search

LeetCode 79. Word Search

Word Search

79. Word Search

79. Word Search

79. Word Search/212. Word Search II--图的back tracking -- tier tree 待续