leetcode 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

分析

回溯法。

代码

class Solution {
public:
    bool search(vector<vector<char>>& board, vector<vector<bool>> &flag, int x, int y, string &word, int start){
        int m = board.size();
        int n = board[0].size();
        if(start == word.length())
            return true;
        if(x < 0 || x >= m || y < 0 || y >= n || flag[x][y] || word.at(start) != board[x][y])
            return false;
        flag[x][y] = true;
        bool ans = search(board, flag, x+1, y, word, start+1) ||
                    search(board, flag, x-1, y, word, start+1) ||
                    search(board, flag, x, y+1, word, start+1) ||
                    search(board, flag, x, y-1, word, start+1);
        flag[x][y] = false;
        return ans;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        if(m == 0)
            return false;
        int n = board[0].size();
        vector<vector<bool> > flag(m, vector<bool> (n, false));
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                    if(search(board, flag, i, j, word, 0))
                        return true;
            }
        }
        return false;
    }
};
阅读更多
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

leetcode Word Search

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭