zoukankan      html  css  js  c++  java
  • [LeetCode] 79. Word Search(单词查找)

    Description

    Given an m x n board and a word, find if the word exists in the grid.
    给定一个 m x nboard 和一个单词 word,判断能不能在 board 里找到该单词。

    The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
    单词可以由板子内若干相邻的单元格组成,这里的相邻指水平或垂直方向的相邻。同一个单元格最多只能使用一次。

    Examples

    Example 1

    Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
    Output: true
    

    Example 2

    Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
    Output: true
    

    Example 3

    Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
    Output: false
    

    Constraints

    • m == board.length
    • n = board[i].length
    • 1 <= m, n <= 200
    • 1 <= word.length <= 103
    • board and word consists only of lowercase and uppercase English letters.

    Solution

    暴力搜索就完事了。不过在搜索的时候需要注意,对于不符合条件的情况,要尽快停止搜索。至于如何标记已经访问过的单元,这里采用了一个 visited 数组,代码如下:

    class Solution {
        fun exist(board: Array<CharArray>, word: String): Boolean {
            val visited = Array(board.size) { BooleanArray(board[0].size) }
            for (i in board.indices) {
                for (j in board[i].indices) {
                    if (backtrack(board, i, j, word, 0, visited)) {
                        return true
                    }
                }
            }
            return false
        }
    
        private fun backtrack(board: Array<CharArray>, i: Int, j: Int, word: String, index: Int, visited: Array<BooleanArray>): Boolean {
            if (index == word.length) {
                return true
            }
            if (i !in board.indices || j !in board[i].indices) {
                return false
            }
            if (visited[i][j] || board[i][j] != word[index]) {
                return false
            }
            visited[i][j] = true
            val result = backtrack(board, i + 1, j, word, index + 1, visited) ||
                    backtrack(board, i - 1, j, word, index + 1, visited) ||
                    backtrack(board, i, j + 1, word, index + 1, visited) ||
                    backtrack(board, i, j - 1, word, index + 1, visited);
            visited[i][j] = false
            return result
        }
    }
    
  • 相关阅读:
    uboot的Makefile分析
    S3C2440上触摸屏驱动实例开发讲解(转)
    linux嵌入式驱动软件开发(csdnblog)
    [连接]研究MSN的一些参考资料(MSNP15)
    关于Asp.net中使用以下代码导出Excel表格的问题
    FCKEditor在Asp.net的安装
    奥运后,接手两个项目,PECT培训,CIW培训,系分考试...........一堆流水帐
    [转]甩掉数据字典,让Sql Server数据库也来一个自描述
    SQL Server 调优将会用到的非常好的DMV
    SQL Server 监视数据文件大小变化
  • 原文地址:https://www.cnblogs.com/zhongju/p/14093133.html
Copyright © 2011-2022 走看看