回溯也刷完了,再从头总结一下,照例从简到难。
Word Search 原题地址:
https://oj.leetcode.com/problems/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
.
先找首字母,然后在该字母邻居中找下一个字母,注意board里每个字母只能最多使用一次。
public class Solution {
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0)
return false;
int row = board.length;
int column = board[0].length;
boolean[][] path = new boolean[row][column];
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++) {
if (board[i][j] == word.charAt(0)) {
path[i][j] = true;
if (word.length()==1 || exist(board, word.substring(1), path, i, j))
return true;
path[i][j] = false;
}
}
return false;
}
private boolean exist(char[][] board, String word,boolean[][] path, int i, int j) {
if (word.length() == 0)
return true;
int row = board.length;
int column = board[0].length;
int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int d = 0; d < direction.length; d++) {
int _i = i + direction[d][0];
int _j = j + direction[d][1];
if (_i >= 0 && _i < row && _j >= 0 && _j < column && board[_i][_j] == word.charAt(0) && !path[_i][_j]) {
path[_i][_j] = true;
if (word.length() == 1 || exist(board, word.substring(1), path, _i, _j))
return true;
path[_i][_j] = false;
}
}
return false;
}
}