【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】

【079-Word Search(单词搜索)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

  word = "ABCCED", -> returns true,

  word = "SEE", -> returns true,

  word = "ABCB", -> returns false.

题目大意

  给定一个board字符矩阵,可以从任意一个点开始经过上下左右的方式走,每个点只能走一次,如果存在一条路走过的字符等于给定的字符串,那么返回true

解题思路

  以每一个点作为起点,使用回溯法进行搜索

代码实现

算法实现类

public class Solution {

    public boolean exist(char[][] board, String word) {
        // 【注意我们假定输入的参数都是合法】

        // 访问标记矩阵,初始值默认会设置为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 (search(board, visited, i, j, word, new int[]{0})) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @param board   字符矩阵
     * @param visited 访问标记矩阵
     * @param row     访问的行号
     * @param col     访问的列号
     * @param word    匹配的字符串
     * @param idx     匹配的位置,取数组是更新后的值可以被其它引用所见
     * @return
     */
    private boolean search(char[][] board, boolean[][] visited, int row, int col, String word, int[] idx) {
        // 如果搜索的位置等于字串的长度,说明已经找到找到匹配的了
        if (idx[0] == word.length()) {
            return true;
        }

        boolean hasPath = false;
        // 当前位置合法
        if (check(board, visited, row, col, word, idx[0])) {
            // 标记位置被访问过
            visited[row][col] = true;
            idx[0]++;
            // 对上,右,下,左四个方向进行搜索
            hasPath = search(board, visited, row - 1, col, word, idx ) // 上
                    || search(board, visited, row, col + 1, word, idx) // 右
                    || search(board, visited, row + 1, col, word, idx) // 下
                    || search(board, visited, row, col - 1, word, idx); // 左

            // 如果没有找到路径就回溯
            if (!hasPath) {
                visited[row][col] = false;
                idx[0]--;
            }
        }

        return hasPath;
    }

    /**
     * 判定访问的位置是否合法
     *
     * @param board   字符矩阵
     * @param visited 访问标记矩阵
     * @param row     访问的行号
     * @param col     访问的列号
     * @param word    匹配的字符串
     * @param idx     匹配的位置
     * @return
     */

    public boolean check(char[][] board, boolean[][] visited, int row, int col, String word, int idx) {
        return row >= 0 && row < board.length // 行号合法
                && col >= 0 && col < board[0].length // 列号合法
                && !visited[row][col] // 没有被访问过
                && board[row][col] == word.charAt(idx); // 字符相等
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47248121

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-01 10:46:44

【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】的相关文章

LeetCode 0079. Word Search单词搜索【Python】

LeetCode 0079. Word Search单词搜索[Medium][Python][DFS] Problem LeetCode 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 horiz

lintcode 中等题:word search 单词搜索

题目 单词搜索 给出一个二维的字母板和一个单词,寻找字母板网格中是否存在这个单词. 单词可以由按顺序的相邻单元的字母组成,其中相邻单元指的是水平或者垂直方向相邻.每个单元中的字母最多只能使用一次. 样例 给出board = [ "ABCE", "SFCS", "ADEE" ] word = "ABCCED", ->返回 true, word = "SEE",-> 返回 true, word = 

[LeetCode]题解(python):079 Word Search

题目来源 https://leetcode.com/problems/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

(Java) LeetCode 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 us

LeetCode 79. Word Search单词搜索 (C++)

题目: 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 b

【LeetCode-面试算法经典-Java实现】【058-Length of Last Word (最后一个单词的长度)】

[058-Length of Last Word (最后一个单词的长度)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return

【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】

[139-Word Break(单词拆分)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", di

【LeetCode-面试算法经典-Java实现】【152-Reverse Words in a String(反转字符串中的单词)】

[152-Reverse Words in a String(反转字符串中的单词)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". 题目大意 给定一个字符串,将其反转,其的字词不转 解题思路

【LeetCode-面试算法经典-Java实现】【030-Substring with Concatenation of All Words(串联所有单词的子串)】

[030-Substring with Concatenation of All Words(串联所有单词的子串)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concaten