zoukankan      html  css  js  c++  java
  • LeetCode-Word Search

    很简单的dfs;

     1 class Solution {
     2 public:
     3     bool exist(vector<vector<char> > &board, string word) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (word.empty()) {
     7             return true;
     8         }
     9         if (board.empty()) {
    10             return false;
    11         }
    12         int m = board.size();
    13         int n = board[0].size();
    14         if (word.size() > m * n) {
    15             return false;
    16         }
    17         vector<vector<bool> > visited(m, vector<bool>(n, false));
    18         for (int i = 0; i < m; ++i) {
    19             for (int j = 0; j < n; ++j) {
    20                 if (dfs(board, visited, word, i, j, 0)) {
    21                     return true;
    22                 }
    23             }
    24         }
    25         return false;
    26     }
    27     bool dfs(vector<vector<char> > &board, vector<vector<bool> > &visited, string &word, int r, int c, int k) {
    28         if (r < 0 || r >= board.size() || c < 0 || c >= board[0].size() || visited[r][c]) {
    29             return false;
    30         }
    31         if (k == word.size() - 1) {
    32             return (board[r][c] == word[k]);
    33         }
    34         if (board[r][c] != word[k]) {
    35             return false;
    36         }
    37         visited[r][c] = true;
    38         bool res = dfs(board, visited, word, r - 1, c, k + 1) || dfs(board, visited, word, r + 1, c, k + 1) || dfs(board, visited, word, r, c - 1, k + 1) || dfs(board, visited, word, r, c + 1, k + 1);
    39         visited[r][c] = false;
    40         return res;
    41     }
    42 };
  • 相关阅读:
    Luogu P1067 多项式模拟
    关于事件流,事件冒泡和事件捕获
    JavaScript高程读书笔记
    前端面试题2017
    Bootstrap教程
    jquery实现JSON数据获取
    AJAX基本格式步骤
    【转】XMLHTTP中setRequestHeader参数问题
    warp()和wrapAll()区别
    append()和appendTo(),prepend()和prependTo()区别
  • 原文地址:https://www.cnblogs.com/chasuner/p/wordsearch.html
Copyright © 2011-2022 走看看