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
  • 相关阅读:
    Cron表达式说明
    exe4j 使用记录(二):jar打包exe
    exe4j 使用记录(一):下载、安装及注册
    Sublime Text3添加右键
    jenkins 入门教程
    Visual Studio设置字体及护眼背景色
    Visual Studio 设置C#语言代码格式
    Visual Studio 常用快捷键
    Maven中使用本地JAR包
    oracle 查看锁表及解锁的语句
  • 原文地址:https://www.cnblogs.com/yalphait/p/10384765.html
Copyright © 2011-2022 走看看