LeetCode-Word Search

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/87854500

Description:
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.

题意:给定一个二维字符数组board和一个匹配字符串word,判断数组board中是否存在字符串word;使用的字符必须是相邻的(水平或者垂直方向);

解法:可以考虑利用回溯算法逐个的匹配给定字符串word中的每个字符,利用这种方法的时候需要注意的是我们需要标记已经处理过的字符,因为这里处理的是字符,所以我们利用与256的异或来标记已经处理过的字符;

Java
class Solution {
    public boolean exist(char[][] board, String word) {
        if ("".equals(word)) {
            return true;
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == word.charAt(0) && 
                   existWord(board, word, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean existWord(char[][] board, String word, int row, int col, int pos) {
        if (pos == word.length()) {
            return true;
        }
        if (row < 0 || row >= board.length || col < 0 || 
            col >= board[row].length || board[row][col] != word.charAt(pos)) {
            return false;
        }
        board[row][col] ^= (1 << 8);
        boolean res = existWord(board, word, row + 1, col, pos + 1) ||
            existWord(board, word, row - 1, col, pos + 1) ||
            existWord(board, word, row, col + 1, pos + 1) ||
            existWord(board, word, row, col - 1, pos + 1);
        board[row][col] ^= (1 << 8);
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/87854500