zoukankan      html  css  js  c++  java
  • [leetcode] Word Search

    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.
     
    思路:DFS算法。
    注意点:由于每个字符只能匹配一次,所以匹配成功将该字符置为无用字符,比如‘#’等,然后继续匹配下一个字符。
     
    class Solution
    {
    public:
      Solution(): isTrue(false) {}
    
    private:
      void dfs(vector<vector<char> > &board,string word, int x, int y, int index)
      {
        if(index == word.size()) 
        {
          isTrue = true;
          return;
        }
        
        if(isTrue) return;
        if(x < 0 || x >= board.size()) return;
        if(y < 0 || y >= board[0].size()) return;
        if(board[x][y] != word[index]) return;
    
        board[x][y] = '#';
        dfs(board, word, x-1, y, index+1);
        dfs(board, word, x+1, y, index+1);
        dfs(board, word, x, y-1, index+1);
        dfs(board, word, x, y+1, index+1);
        board[x][y] = word[index];
      }
    public:
      bool exist(vector<vector<char> > &board, string word)
      {
        if(board.empty() || board[0].empty()) return false;
    
        isTrue = false;
        int index = 0;
        for(int i=0; i<board.size(); i++)
        {
          for(int j=0; j<board[0].size(); j++)
          {
            if(!isTrue)
              dfs(board, word, i, j, index);
          }
        }
    
        return isTrue;
      }
    
    private:
      bool isTrue;
    };
  • 相关阅读:
    150个JS特效脚本
    .sql文件被加密恢复
    Alpha865qqz.id 加密数据库恢复
    最新incaseformat 病毒删除文件恢复
    Oracle MISSING00000文件故障恢复
    asm 磁盘分区丢失恢复----惜分飞
    oracle数据文件0kb恢复
    ORA-600 16703--oracle介质被注入恶意脚本
    GANDCRAB病毒oracle数据库恢复
    文件系统损坏,oracle数据库恢复
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4484537.html
Copyright © 2011-2022 走看看