Description
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Note: There will be some test cases with a board or a word larger than constraints to test if your solution is using pruning.
Examples
Example 1:
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true
Example 2:
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
Output: true
Example 3:
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.
解题思路
这个也没啥说的,就是深搜
代码
class Solution {
public boolean process(char[][] board, String word, int pos, int row, int col){
if (pos == word.length()) {
return true;
}
int max_row = board.length;
int max_col = board[0].length;
if(row < 0 || row >= max_row || col < 0 || col >= max_col || board[row][col] != word.charAt(pos)){
return false;
}
board[row][col] = ' ';
if(process(board, word, pos + 1, row, col + 1)){
return true;
}
if(process(board, word, pos + 1, row, col - 1)){
return true;
}
if(process(board, word, pos + 1, row + 1, col)){
return true;
}
if(process(board, word, pos + 1, row - 1, col)){
return true;
}
board[row][col] = word.charAt(pos);
return false;
}
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[0].length; j++){
if(process(board, word, 0, i, j)){
return true;
}
}
}
return false;
}
}
随笔
有点好玩的是我这份跑下来lc上耗时62ms,但是从他的accept solution里面扒下来一个5ms的代码跑一下也要63ms,所以这个跑的时间是不是不仅仅和算法效率挂钩啊。