Leetcode -- Word Search(Important!)

来源:互联网 发布:苍老师在哪里看 知乎 编辑:程序博客网 时间:2024/04/28 01:29

题目:
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 exist(vector<vector<char>>& board, string word) {        rowLen = board.size();        colLen = board[0].size();        for(int i =0; i != rowLen; i++)        {            for(int j = 0; j != colLen; j ++)            {               if(exist(board, word, i, j, 0))                    return true;            }        }        return false;    }private:    int rowLen, colLen;    bool exist(vector<vector<char>>& board, string word, int i, int j, int pos)    {        if(board[i][j] != word[pos] || board[i][j] ==' ')        {            return false;        }        if(pos == word.size() -1)        {            return true;        }        char ch = board[i][j];        board[i][j] = ' ';        bool next = i > 0 && exist(board, word, i -1, j, pos+1) ||i < rowLen - 1 && exist(board, word, i + 1, j, pos + 1) ||                    j > 0 && exist(board, word, i, j-1, pos + 1) || j < colLen - 1 && exist(board, word, i, j+1, pos + 1);        board[i][j] = ch;        return next;    }};

PS:尽管自己可以将大致做法写出来,但总是写不好代码,该多练练啊!

0 0
原创粉丝点击