文章标题

来源:互联网 发布:酶标仪数据怎么看 编辑:程序博客网 时间:2024/04/30 07:01
  1. 问题描述
    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 =

    [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
    ]

    word = “ABCCED”, -> returns true,
    word = “SEE”, -> returns true,
    word = “ABCB”, -> returns false.

  2. 解决思路
    深搜硬刚。不要怂就好。

  3. 代码

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {        if (word.size() == 0)            return true;        int n = board.size();        if (n == 0)            return false;        int m = board[0].size();        vector<vector<bool>> flags;        for (int i = 0; i < n; ++i) {            flags.push_back(vector<bool>());            for (int j = 0; j < m; ++j)                flags[i].push_back(true);        }        for (int i = 0; i < n; ++i) {            for (int j = 0; j < m; ++j) {                flags[i][j] = false;                if (helper(board,word,flags,i,j))                    return true;                flags[i][j] = true;            }        }        return false;    }    bool helper(vector<vector<char>>& board,string word,vector<vector<bool>>& flags,int x, int y) {        if (word.size() == 0)            return true;        if (word.size() == 1 && word[0] == board[x][y])            return true;        if (word[0] == board[x][y]) {            flags[x][y] = false;            if(x > 0 && flags[x-1][y] && helper(board,word.substr(1,word.size()-1),flags,x-1,y))                return true;            if(y > 0 && flags[x][y-1] && helper(board,word.substr(1,word.size()-1),flags,x,y-1))                return true;            if(x < board.size() - 1 && flags[x+1][y] && helper(board,word.substr(1,word.size()-1),flags,x+1,y))                return true;            if(y < board[0].size() -1 && flags[x][y+1] && helper(board,word.substr(1,word.size()-1),flags,x,y+1))                return true;            flags[x][y] = true;        }        return false;    }};
0 0