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

    AC code:

    class Solution {
    public:
        bool exist(vector<vector<char>>& board, string word) {
            if (board.size() == 0) return false;
            int len = word.length();
            int row = board.size(), col = board[0].size();
            for (int i = 0; i < row; ++i) {
                for (int j = 0; j < col; ++j) {
                    if (board[i][j] == word[0]) {
                        if (helper(i, j, word, 0, board))
                            return true;
                    }
                }
            }
            return false;
        }
        
        bool helper(int x, int y, string& word, int index, vector<vector<char>>& board) {
            if (index >= word.length()) return true;
            if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size()) return false;
            if (board[x][y] == word[index++]) {
                char c = board[x][y];
                board[x][y] = '#';
                bool res = helper(x+1, y, word, index, board) || helper(x-1, y, word, index, board) ||
                           helper(x, y+1, word, index, board) || helper(x, y-1, word, index, board);
                board[x][y] = c;
                return res;
            }
            return false;
        }
    };
    
    Runtime: 20 ms, faster than 80.42% of C++ online submissions for Word Search.
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    观光公交
    审查(银)
    小木棍 && 愤怒的小鸟
    SDOI2008 仪仗队 && SDOI2012 Longge的问题 && q
    斗地主 && Mayan游戏 && 作业调度方案
    过河
    跳跳棋
    count
    Cow Tennis Tournament
    luogu P1534不高兴的津津(升级版)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9843888.html
Copyright © 2011-2022 走看看