zoukankan      html  css  js  c++  java
  • Leetcode79 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.(Medium)

    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.

    分析: 这几道是连着的搜索题,就是对四个方向搜索有没有满足条件(word[i]中)的元素,有的话则进一步搜索下去。

    代码:

     1 class Solution {
     2 private:
     3     bool flag = false;
     4     int dx[4] = {-1,0,0,1};
     5     int dy[4] = {0,1,-1,0};
     6     void helper(vector<vector<char>>& board, int x, int y, int i, const string& word) {
     7         if (flag == true) {
     8             return;
     9         }
    10         if (i == word.size()) {
    11             flag = true;
    12             return;
    13         }
    14         for (int j = 0; j < 4; ++j) {
    15             int nx = x + dx[j];
    16             int ny = y + dy[j];
    17             if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size() && board[nx][ny] == word[i]) {
    18                 char temp = board[nx][ny];
    19                 board[nx][ny] = 'X';
    20                 helper(board, nx, ny, i + 1, word);
    21                 board[nx][ny] = temp;
    22             }
    23         }
    24     }
    25 public:
    26     bool exist(vector<vector<char>>& board, string word) {
    27         int sz = word.size();
    28         for (int i = 0; i < board.size(); ++i) {
    29             for (int j = 0; j < board[0].size(); ++j) {
    30                 if (board[i][j] == word[0]) {
    31                     vector<vector<char>> temp = board;
    32                     temp[i][j] = 'X';
    33                     helper(temp, i, j, 1, word);
    34                     if (flag == true) {
    35                         return true;
    36                     }
    37                 }
    38             }
    39         }
    40         return false;
    41     }
    42 };
     
  • 相关阅读:
    Java Web系统经常使用的第三方接口
    Direct UI
    Python 分析Twitter用户喜爱的推文
    数据挖掘十大经典算法(9) 朴素贝叶斯分类器 Naive Bayes
    利用Excel批量高速发送电子邮件
    普林斯顿大学数学系的崛起
    Node.js学习
    映射 SQL 和 Java 类型
    Nutch配置
    OGNL
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5922156.html
Copyright © 2011-2022 走看看