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

    题意

    矩阵中是否存在一条连续路径是所给字符串

    题解

    用的dfs回溯,时间效率不算很高

     1 class Solution {
     2 public:
     3     int dire[4][2] = { -1,0,1,0,0,1,0,-1 };
     4     bool found(vector<vector<char>>& board, int x, int y, string word , int i) {
     5         if (i == word.length()-1)return true;
     6         int m = board.size(), n = board[0].size();
     7         board[x][y] = -1;
     8         for (int j = 0; j < 4; j++) {
     9             int nextx = x + dire[j][0], nexty = y + dire[j][1];
    10             if (nextx < m&&nextx >= 0 && nexty < n&&nexty >= 0 && word[i + 1] == board[nextx][nexty])
    11                 if (found(board, nextx, nexty, word, i + 1))
    12                     return true;
    13         }
    14         board[x][y] = word[i];
    15         return false;
    16     }
    17     bool exist(vector<vector<char>>& board, string word) {
    18         int m = board.size(), n = board[0].size();
    19         for (int i = 0; i < m; i++)
    20             for (int j = 0; j < n; j++)
    21                 if (word[0] == board[i][j] && found(board, i, j, word, 0))
    22                     return true;
    23         return false;
    24     }
    25 };
    View Code
  • 相关阅读:
    #考研碎碎念#
    #考研笔记#计算机之病毒
    #考研笔记#计算机之多媒体应用
    #考研笔记#计算机之PPT问题
    第六章深入理解类
    第五章方法
    类的基本教程
    类型存储变量
    C#和.net框架
    C#编程概述
  • 原文地址:https://www.cnblogs.com/yalphait/p/10384765.html
Copyright © 2011-2022 走看看