题目:
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.(Medium)
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
.
分析: 这几道是连着的搜索题,就是对四个方向搜索有没有满足条件(word[i]中)的元素,有的话则进一步搜索下去。
代码:
1 class Solution { 2 private: 3 bool flag = false; 4 int dx[4] = {-1,0,0,1}; 5 int dy[4] = {0,1,-1,0}; 6 void helper(vector<vector<char>>& board, int x, int y, int i, const string& word) { 7 if (flag == true) { 8 return; 9 } 10 if (i == word.size()) { 11 flag = true; 12 return; 13 } 14 for (int j = 0; j < 4; ++j) { 15 int nx = x + dx[j]; 16 int ny = y + dy[j]; 17 if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size() && board[nx][ny] == word[i]) { 18 char temp = board[nx][ny]; 19 board[nx][ny] = ‘X‘; 20 helper(board, nx, ny, i + 1, word); 21 board[nx][ny] = temp; 22 } 23 } 24 } 25 public: 26 bool exist(vector<vector<char>>& board, string word) { 27 int sz = word.size(); 28 for (int i = 0; i < board.size(); ++i) { 29 for (int j = 0; j < board[0].size(); ++j) { 30 if (board[i][j] == word[0]) { 31 vector<vector<char>> temp = board; 32 temp[i][j] = ‘X‘; 33 helper(temp, i, j, 1, word); 34 if (flag == true) { 35 return true; 36 } 37 } 38 } 39 } 40 return false; 41 } 42 };
时间: 2024-10-13 00:14:50