关闭

leetcode Word Search

标签: 面试题leetcode算法
1497人阅读 评论(0) 收藏 举报
分类:

题目

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;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:228923次
    • 积分:3281
    • 等级:
    • 排名:第10693名
    • 原创:100篇
    • 转载:11篇
    • 译文:2篇
    • 评论:30条
    文章分类
    最新评论