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.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.看这个面板中是否存在字符串,第一反应还是利用dfs进行求解
class Solution { public: bool exist(vector<vector<char>>& board, string word) { if (board.empty() || board[0].empty()) return false; int n = board.size(), m = board[0].size(); bool **record = new bool*[n]; for (int i = 0; i<n; i++) { record[i] = new bool[m]; memset(record[i], 0, sizeof(bool)*m); } for (int i = 0; i<n; i++) { for (int j = 0; j<m; j++) { if (go(board, record, i, j, word)) return true; } } return false; } bool go(vector<vector<char>> &board, bool **&record, int i, int j, string s) { if (s.empty()) return true; if (board[i][j] == s[0]) { if (s.size() == 1) return true; record[i][j] = 1; if (i>0 && !record[i - 1][j] && go(board, record, i - 1, j, s.substr(1))) { return true; } if (i<board.size() - 1 && !record[i + 1][j] && go(board, record, i + 1, j, s.substr(1))) { return true; } if (j>0 && !record[i][j - 1] && go(board, record, i, j - 1, s.substr(1))) { return true; } if (j<board[0].size() - 1 && !record[i][j + 1] && go(board, record, i, j + 1, s.substr(1))) { return true; } record[i][j] = 0; return false; } else return false; } };