【题目】
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
.
【题意】
给定一个二维字母矩阵board和单词word, 判断单词是否存在于board中,单词可以用board中的相邻字母连接而成,可以是上下相邻,也可以是左右相邻。同一个cell不能重复使用。
【思路】
先在board中找到word的第一个字符,然后用DFS判断
【代码】
class Solution { public: vector<vector<bool> > isVisited; bool search(vector<vector<char> >&board, int i, int j, string&word, int k){ // board[i][j]和word[k-1]吻合,以此为起点判断剩余的字符 isVisited[i][j]=true; if(k==word.length())return true; //判断上方的位置 if(i-1>=0 && !isVisited[i-1][j] && board[i-1][j]==word[k] && search(board, i-1, j, word, k+1))return true; //判断右面的位置 if(j+1<board[0].size() && !isVisited[i][j+1] && board[i][j+1]==word[k] && search(board, i, j+1, word, k+1))return true; //判断下面的位置 if(i+1<board.size() && !isVisited[i+1][j] && board[i+1][j]==word[k] && search(board, i+1, j, word, k+1))return true; //判断左面的位置 if(j-1>=0 && !isVisited[i][j-1] && board[i][j-1]==word[k] && search(board, i, j-1, word, k+1))return true; isVisited[i][j]=false; return false; } bool exist(vector<vector<char> > &board, string word) { if(word.length()==0)return false; int rows = board.size(); if(rows==0) return false; int cols = board[0].size(); if(cols==0)return false; //定位首字符 isVisited=vector<vector<bool> >(rows, vector<bool>(cols, false)); for(int i=0; i<rows; i++){ for(int j=0; j<cols; j++){ if(board[i][j]==word[0]){ if(search(board, i, j, word, 1))return true; } } } return false; } };
LeetCode: Word Search [079],布布扣,bubuko.com
时间: 2024-10-11 13:24:41