leetcode Word Search

小鱼儿 2022-08-02 04:38 276阅读 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

分析

回溯法。

代码

  1. class Solution {
  2. public:
  3. bool search(vector<vector<char>>& board, vector<vector<bool>> &flag, int x, int y, string &word, int start){
  4. int m = board.size();
  5. int n = board[0].size();
  6. if(start == word.length())
  7. return true;
  8. if(x < 0 || x >= m || y < 0 || y >= n || flag[x][y] || word.at(start) != board[x][y])
  9. return false;
  10. flag[x][y] = true;
  11. bool ans = search(board, flag, x+1, y, word, start+1) ||
  12. search(board, flag, x-1, y, word, start+1) ||
  13. search(board, flag, x, y+1, word, start+1) ||
  14. search(board, flag, x, y-1, word, start+1);
  15. flag[x][y] = false;
  16. return ans;
  17. }
  18. bool exist(vector<vector<char>>& board, string word) {
  19. int m = board.size();
  20. if(m == 0)
  21. return false;
  22. int n = board[0].size();
  23. vector<vector<bool> > flag(m, vector<bool> (n, false));
  24. for(int i = 0; i < m; i++){
  25. for(int j = 0; j < n; j++){
  26. if(search(board, flag, i, j, word, 0))
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. };

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读