LeetCode | 79. Word Search

mac2024-11-24  28

 

题目:

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.

 

代码:

class Solution { public: struct Point { int x, y; Point(int xx, int yy) { x = xx; y = yy; } }; void searchWord(vector<vector<char>>& board, string& word, int idx, Point cur, vector<vector<bool>> record, bool& isFound) { if(isFound || idx == word.length()) { isFound = true; return; } int r = board.size(), c = board[0].size(); if(cur.x + 1 < r && board[cur.x + 1][cur.y] == word[idx] && !record[cur.x + 1][cur.y]) { record[cur.x + 1][cur.y] = true; searchWord(board, word, idx+1, Point(cur.x + 1, cur.y), record, isFound); record[cur.x + 1][cur.y] = false; } if(cur.x - 1 >= 0 && board[cur.x - 1][cur.y] == word[idx] && !record[cur.x - 1][cur.y] && !isFound) { record[cur.x - 1][cur.y] = true; searchWord(board, word, idx+1, Point(cur.x - 1, cur.y), record, isFound); record[cur.x - 1][cur.y] = false; } if(cur.y + 1 < c && board[cur.x][cur.y + 1] == word[idx] && !record[cur.x][cur.y + 1] && !isFound) { record[cur.x][cur.y + 1] = true; searchWord(board, word, idx+1, Point(cur.x, cur.y + 1), record, isFound); record[cur.x][cur.y + 1] = false; } if(cur.y - 1 >= 0 && board[cur.x][cur.y - 1] == word[idx] && !record[cur.x][cur.y - 1] && !isFound) { record[cur.x][cur.y - 1] = true; searchWord(board, word, idx+1, Point(cur.x, cur.y - 1), record, isFound); record[cur.x][cur.y - 1] = false; } return; } bool exist(vector<vector<char>>& board, string word) { if(word.length() < 1) return true; int r = board.size(); if(r < 1) return false; int c = board[0].size(); if(c < 1) return false; char f = word[0]; for(int i = 0; i<r; i++) { for(int j = 0; j<c; j++) { if(board[i][j] != f) continue; vector<vector<bool>> record(r, vector<bool>(c, false)); record[i][j] = true; bool isFound = false; searchWord(board, word, 1, Point(i, j), record, isFound); if(isFound) return true; } } return false; } };

 

 

 

 

最新回复(0)