zoukankan      html  css  js  c++  java
  • 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 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中每一个元素,判断与word中的第一个字母是否相同,如果相同则在当前位置上去搜索上下左右相邻的单元格的元素是否和当前字母的下一个字母相同,不在搜索范围内或者字母不同就返回false,当搜索的字母数等于word的长度时,也就表明在board找到了这个word。注意每次判断一个字母要标记当前位置以搜索过,以防止字母重复利用。我选择直接更改board元素,以便在后续的判断中不会重复判断此位置,在搜索结束后改回来就可以了。

    程序:

    class Solution {
    public:
        bool exist(vector<vector<char>>& board, string word) {
            h = board.size();
            w = board[0].size();
            for(int i = 0; i < h; i++){
                for(int j = 0; j < w; ++j){
                    if(searchexist(board, word, 0, i, j)) return true;
                }
            }
            return false;
        }
        int searchexist(vector<vector<char>>& board, string &word, int n, int x, int y){
            if(x < 0 || x > h-1 || y < 0 || y > w-1 || word[n] != board[x][y])
                return 0;
            if(n == word.length()-1)
                return 1;
            char temp = board[x][y];
            board[x][y] = 0;
            int flag = searchexist(board, word, n+1, x+1, y)
                     ||searchexist(board, word, n+1, x-1, y)
                     ||searchexist(board, word, n+1, x, y+1)
                     ||searchexist(board, word, n+1, x, y-1);
            board[x][y] = temp;
            return flag;
        }
    private:
        int h, w;
    };
  • 相关阅读:
    poj 3321 Apple Tree
    hdu 1520 Anniversary party
    Light OJ 1089 Points in Segments (II)
    Timus 1018 Binary Apple Tree
    zoj 3299 Fall the Brick
    HFUT 1287 法默尔的农场
    Codeforces 159C String Manipulation 1.0
    GraphQL + React Apollo + React Hook 大型项目实战(32 个视频)
    使用 TypeScript & mocha & chai 写测试代码实战(17 个视频)
    GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)
  • 原文地址:https://www.cnblogs.com/silentteller/p/11128108.html
Copyright © 2011-2022 走看看