首页 > 代码库 > 【LeetCode】Word Search 解题报告

【LeetCode】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 =

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


【解析】

DFS;回溯;递归。

public class Solution {
    char[][] board;
    int m, n;
    
    public boolean exist(char[][] board, String word) {
        if (board == null || word == null) return false;
        if (("").equals(word)) return true;
        
        this.board = board;
        m = board.length;
        n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word.charAt(0)) {
                    char tmp = board[i][j];
                    board[i][j] = '#';
                    if (dfs(i, j, word.substring(1))) return true;
                    board[i][j] = tmp;
                }
            }
        }
        return false;
    }
    
    public boolean dfs(int i, int j,  String word) {
        if (("").equals(word)) return true;
        char tar = word.charAt(0);
        String left = word.substring(1);
        if (i > 0 && board[i - 1][j] == tar) {
            board[i - 1][j] = '#';
            if (dfs(i - 1, j, left)) return true;
            board[i - 1][j] = tar;
        }
        if (j > 0 && board[i][j - 1] == tar) {
            board[i][j - 1] = '#';
            if (dfs(i, j - 1,left)) return true;
            board[i][j - 1] = tar;
        }
        if (i < m - 1 && board[i + 1][j] == tar) {
            board[i + 1][j] = '#';
            if (dfs(i + 1, j, left)) return true;
            board[i + 1][j] = tar;
        }
        if (j < n - 1 && board[i][j + 1] == tar) {
            board[i][j + 1] = '#';
            if (dfs(i, j + 1, left)) return true;
            board[i][j + 1] = tar;
        }
        return false;
    }
}


【LeetCode】Word Search 解题报告