zoukankan      html  css  js  c++  java
  • 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.
    For example,
    Given board =
    [
    ["ABCE"],
    ["SFCS"],
    ["ADEE"]
    ]
    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    Solution: DFS. (For 'visited', using two-dimensional array will be faster than vector<vector>.[90+ms->50+ms])

     1 class Solution {
     2 public:
     3     typedef vector<vector<char> > VECTOR2D;
     4     
     5     bool exist(VECTOR2D &board, string word) {
     6         int N = board.size(), M = board[0].size();
     7         VECTOR2D avail(N, vector<char>(M, 'o'));
     8         for (int i = 0; i < N; ++i)
     9             for (int j = 0; j < M; ++j)
    10                 if (existRe(board, word, 0, i, j, avail))
    11                     return true;
    12         return false;
    13     }
    14 
    15     bool existRe(const VECTOR2D &board, const string &word, int deep, int i, int j, VECTOR2D &avail)
    16     {
    17         int N = board.size(), M = board[0].size();
    18         if (deep == word.size()) return true;
    19         if (i < 0 || i >= N || j < 0 || j >= M) return false;
    20         if (board[i][j] != word[deep] || avail[i][j] == 'x') return false;
    21         
    22         avail[i][j] = 'x';
    23         if (existRe(board, word, deep + 1, i-1, j, avail)) return true;
    24         if (existRe(board, word, deep + 1, i+1, j, avail)) return true;
    25         if (existRe(board, word, deep + 1, i, j-1, avail)) return true;
    26         if (existRe(board, word, deep + 1, i, j+1, avail)) return true;
    27         avail[i][j] = 'o';
    28         
    29         return false;
    30     }
    31 };
  • 相关阅读:
    Python Scrapy 自动爬虫注意细节(3)
    Python Scrapy 验证码登录处理
    Python Scrapy 自动爬虫注意细节(2)
    Python Scrapy 自动爬虫注意细节(1)
    Python 爬虫知识点
    Android权限全记录(转)
    Python 爬虫知识点
    eclipse的Maven项目pom.xml错误信息提示missingxxxjar解决方案
    Hadoop核心架构HDFS+MapReduce+Hbase+Hive内部机理详解
    spark学习系列
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3679648.html
Copyright © 2011-2022 走看看