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 a sequentially adjacent cells, 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 [y] [x] ^ = 256这是标记,表明位置x,y的字母是我们搜索的单词的一部分。
在board [y] [x] ^ = 256之后,字符变为无效字母。在第二个木板[y] [x] ^ = 256之后,
它再次变为有效字母

 

因为先判断board.length,顺序应该是先y后x

 

index小于0不行,等于边界不行

if (y<0 || x<0 || y == board.length || x == board[y].length)

 

这是通过或运算实现的,只要有一个方向通过即可

 

首先是返回true的这种情况,就验证到头了呗

 

最后一个字母不相等也不行

 

class Solution {
    public boolean exist(char[][] board, String word) {
        //cc
        
        //双重for循环,经过每一个点
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[0].length; x++) {
                if (doExist(board, word, y, x, 0))
                    return true;
            }
        }
        
        return false;
    }
    
    public boolean doExist(char[][] board, String word,
                          int y, int x, int i) {
        //word到头,是相等了
        if (i == word.length())
            return true;
        
        //矩阵到头
        if (y < 0 || y >= board.length || x < 0 || x >= board[y].length)
            return false;
        
        //最后一位不相等
        if (board[y][x] != word.charAt(i))
            return false;
        
        //扩展
        board[y][x] ^= 256;
        boolean exist = doExist(board, word, y - 1, x, i + 1) ||
                        doExist(board, word, y + 1, x, i + 1) ||
                        doExist(board, word, y, x - 1, i + 1) ||
                        doExist(board, word, y, x + 1, i + 1);
        board[y][x] ^= 256;
        
        return exist;
    }
}
View Code

 

 
posted @ 2020-08-29 00:12  苗妙苗  阅读(173)  评论(0编辑  收藏  举报