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)
  • 相关阅读:
    linux tar order
    Linux驱动学习步骤(转载)
    汇编指令(转载)
    拓扑排序
    python 三维坐标图
    python 矩阵
    spring 之 IOC 依赖注入详解
    spring 下载
    Struts数据验证
    拦截器配置
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9843888.html
Copyright © 2011-2022 走看看