zoukankan      html  css  js  c++  java
  • 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 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 =

    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    
    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.
    dfs + backtracing
    首先遍历矩阵中的每个元素,是否等于word的第一个字符,如果等于进行dfs。在dfs中,如果当前元素周围的元素未被遍历过、并且等于word里的下一个字符,就再对这个元素进行dfs(backtracing)

    这是212的先头题。

    public class Solution {
        public boolean exist(char[][] board, String word) {
            if (word == null || word.length() == 0) {
                return false;
            }
            boolean[][] visited = new boolean[board.length][board[0].length];
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == word.charAt(0)) {
                        if (helper(visited, board, i, j, word, 1)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        public boolean helper(boolean[][] visited, char[][] board, int i, int j, String word, int index) {
            if (index == word.length()) {
                return true;
            }
            visited[i][j] = true;
            boolean re = false;
            if (!re && i > 0 && board[i - 1][j] == word.charAt(index) && !visited[i - 1][j]) {
                re = helper(visited, board, i - 1, j, word, index + 1);
            }
            if (!re && i < board.length - 1 && board[i + 1][j] == word.charAt(index) && !visited[i + 1][j]) {
                re = helper(visited, board, i + 1, j, word, index + 1);
            }
            if (!re && j > 0 && board[i][j - 1] == word.charAt(index) && !visited[i][j - 1]) {
                re = helper(visited, board, i, j - 1, word, index + 1);
            }
            if (!re && j < board[0].length - 1 && board[i][j + 1] == word.charAt(index) && !visited[i][j + 1]) {
                re = helper(visited, board, i, j + 1, word, index + 1);
            }
            visited[i][j] = false;
            return re;
        }
    }
    
  • 相关阅读:
    线上六个性能问题案例分享
    通达OA 前台任意用户登录漏洞复现
    CVE-2019-11043-Nginx PHP 远程代码执行
    CVE-2019-10758-Mongo-express-远程代码执行
    CVE-2017-7529-Nginx越界读取缓存漏洞
    add_header被覆盖 -配置错误
    目录穿越漏洞 -配置错误
    CRLF注入漏洞 -配置错误
    CVE-2019-12409-Apache Solr JMX服务远程代码执行
    CVE-2017-12149-JBoss 5.x/6.x 反序列化
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7223490.html
Copyright © 2011-2022 走看看