第十六周:[leetCode] 79. Word Search

来源:互联网 发布:崩坏3rd unity源码 编辑:程序博客网 时间:2024/06/04 01:26

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.

解题思路:典型深度搜索题目,可通过遍历数组查找单词的第一个字母,通过标志已寻路径搜索整个单词。

 bool find(vector<vector<char>>& board, string& word, int index, int x, int y){  if(board[x][y] != word[index]) return false;  if(index == word.size() - 1) return true;  char temp = board[x][y];  bool res = false;  // 标志已访问的路径  board[x][y] = '*';  // 按左右上下的顺序搜寻单词的下一字母  if(x > 0) res = find(board, word, index + 1, x - 1, y);  if(!res && x < board.size() - 1) res = find(board, word, index + 1, x + 1, y);  if(!res && y < board[0].size() - 1) res = find(board, word, index + 1, x , y + 1);  if(!res && y > 0) res = find(board, word, index + 1, x , y - 1);  // 查找完后恢复原字母  board[x][y] = temp;  return res;}bool exist(vector<vector<char>>& board, string word) { if(!board.empty() && !board[0].empty() && word.size() != 0){    // 遍历vector<vector<char>>数组    for(int r = 0; r < board.size(); r++){      for(int c = 0; c < board[0].size(); c++){        if(find(board, word, 0, r, c))          return true;      }    }  }  return false;}
原创粉丝点击