题目:
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 =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
题意:
从给定的二维数组中找到给定的词语。
这个词可以使用字母顺序相邻的格子组成,相邻的格子是指水平或垂直相邻。相同的字母格子不得使用超过一次。
思路:
DFS(深度搜索)+Backtracking(回溯法)问题。将单词的每个字符与二维数组中的字符相比,全部相符返回true。
代码:16ms
C++版:
class Solution { public: bool exist(vector<vector<char>>& board, string word) { int M,N,i,j,sLen = word.size(); if( (M=board.size()) && (N=board[0].size()) && sLen) { for(i=0; i<M; ++i) for(j=0; j<N; ++j) if(dfs(board, i, j, word, 0, M, N, sLen)) return true; } return false; } private: bool dfs(vector<vector<char>>& board, int row, int col, const string &word, int start, int M, int N, int sLen) { char curC; bool res = false; if( (curC = board[row][col]) != word[start]) return false; if(start==sLen-1) return true; board[row][col] = '*'; if(row>0) res = dfs(board, row-1, col, word, start+1, M, N, sLen); if(!res && row < M-1) res = dfs(board, row+1, col, word, start+1, M, N, sLen); if(!res && col > 0) res = dfs(board, row, col-1, word, start+1, M, N, sLen); if(!res && col < N-1) res = dfs(board, row, col+1, word, start+1, M, N, sLen); board[row][col] = curC; return res; } };java版:9ms
public class Solution { public boolean exist(char[][] board, String word) { char[] words = word.toCharArray(); for(int i=0; i<board.length; i++){ for(int j=0; j<board[0].length; j++){ if(exist(board, i, j, words, 0)){ return true; } } } return false; } private boolean exist(char[][] board, int i, int j, char[] words, int k){ if(k==words.length){ return true; } if(i<0 || j<0 || i==board.length || j==board[i].length){ return false; } if(board[i][j]!=words[k]){ return false; } board[i][j] ^= 256; boolean exist = exist(board, i, j+1, words, k+1) || exist(board, i, j-1, words, k+1) || exist(board, i+1, j, words, k+1) || exist(board, i-1, j, words, k+1); board[i][j] ^= 256; return exist; } }