• 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
     
  • 相关阅读:
    CF1324F Maximum White Subtree
    CF1204C Anna, Svyatoslav and Maps
    CF1187E Tree Painting
    CF1304E 1-Trees and Queries
    深入探究jvm之类装载器
    深入探究jvm之GC的算法及种类
    深入探究jvm之GC的参数调优
    spring源码解析之AOP原理
    spring注解扫描组件注册
    cas-client单点登录客户端拦截请求和忽略/排除不需要拦截的请求URL的问题
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13580420.html
Copyright © 2020-2023  润新知