- Word search
Leetcode-cn.com/problems/wo… Given an M x N two-dimensional character grid board and a string word. Return true if Word exists in the grid; Otherwise, return false.
Words must be formed in alphabetical order by letters in adjacent cells, where “adjacent” cells are those that are horizontally or vertically adjacent. Letters in the same cell are not allowed to be reused.
board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED”
class Solution { public: bool exist(vector<vector<char>>& board, string word) { // board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" int h = board.size(), w = board[0].size(); vector<vector<int>> visited(h, vector<int>(w)); For (int I = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (isEqual(board, visited, word, i, j, 0)) { return true; } } } return false; } bool isEqual(vector<vector<char>>& board, vector<vector<int>>& visited, string& s, int i, int j, Int k) {if (board[I][j]! = s[k]) { return false; } if (k == s.length() - 1) { return true; } visited[i][j] = true; vector<pair<int,int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; bool result = false; // After the current position of the letter matching, the next letter matching k+1 // grid traversal 1. For (const auto& dir: Directions) {int newx = I + dir.first, newy = j + dir.second; for (const auto& dir: Directions) {int newx = I + dir.first, newy = j + dir.second; if (newx >= 0 && newx < board.size() && newy >= 0 && newy < board[0].size()) { if (! visited[newx][newy]) { bool flag = isEqual(board, visited, s, newx, newy, k + 1); if (flag) { result = true; break; } } } } visited[i][j] = false; return result; }};Copy the code