[LeetCode] Word Search 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 = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. 递归 Java: public class Solution { public boolean exist(char[][] board, String word) { // Start typing your Java solution below // DO NOT write main() function if(word.length() == 0) return true; int h = board.length; if(h == 0) return false; int w = board[0].length; boolean[][] flag = new boolean[h][w]; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(word.charAt(0) == board[i][j]){ if(func(board, word, 0, w, h, j, i, flag)) return true; } } } return false; } public boolean func(char[][] board, String word, int spos, int w, int h, int x, int y, boolean[][] flag){ if(spos == word.length()) return true; if(x < 0 || x >= w || y < 0 || y >= h) return false; if(flag[y][x] || board[y][x] != word.charAt(spos)) return false; flag[y][x] = true; // up if(func(board, word, spos + 1, w, h, x, y-1, flag)){ return true; } // down if(func(board, word, spos + 1, w, h, x, y+1, flag)){ return true; } // left if(func(board, word, spos + 1, w, h, x-1, y, flag)){ return true; } // right if(func(board, word, spos + 1, w, h, x+1, y, flag)){ return true; } flag[y][x] = false; return false; } } c++ class Solution { public: bool exist(vector<vector<char> > &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function if(word.size() == 0) return true; int h = board.size(); if(h == 0) return false; int w = board[0].size(); vector<vector<bool> > flag(h, vector<bool>(w, false)); for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(board[i][j] == word[0]){ if(func(board, word, w, h, j, i, 0, flag)) return true; } } } return false; } bool func(vector<vector<char> > board, string word, int w, int h, int x, int y, int spos, vector<vector<bool> > flag){ if(spos == word.size()) return true; if(x < 0 || x >= w || y < 0 || y >= h) return false; if(flag[y][x] || word[spos] != board[y][x]) return false; flag[y][x] = true; // up if(func(board, word, w, h, x, y - 1, spos + 1, flag)){ return true; } if(func(board, word, w, h, x, y + 1, spos + 1, flag)){ return true; } if(func(board, word, w, h, x - 1, y, spos + 1, flag)){ return true; } if(func(board, word, w, h, x + 1, y, spos + 1, flag)){ return true; } flag[y][x] = false; return false; } };
本文提供了一种解决LeetCode单词搜索问题的方法。通过递归算法,在给定的二维字符网格中查找指定单词是否存在,考虑了相邻单元格的水平和垂直连接,并确保同一单元格字母不会被重复使用。

被折叠的 条评论
为什么被折叠?



