原题网址:https://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 =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
"SEE"
, -> returns
true
,
"ABCB"
, -> returns
false
.
方法:深度优先搜索。
public class Solution {
private boolean find(char[][] board, boolean[][] used, char[] wa, int pos, int row, int col) {
if (pos == wa.length) return true;
if (row < 0 || row >= board.length || col < 0 || col >= board[row].length) return false;
if (used[row][col]) return false;
if (wa[pos] != board[row][col]) return false;
used[row][col] = true;
if (find(board, used, wa, pos+1, row, col-1)) return true;
if (find(board, used, wa, pos+1, row, col+1)) return true;
if (find(board, used, wa, pos+1, row-1, col)) return true;
if (find(board, used, wa, pos+1, row+1, col)) return true;
used[row][col] = false;
return false;
}
public boolean exist(char[][] board, String word) {
boolean[][] used = new boolean[board.length][board[0].length];
char[] wa = word.toCharArray();
for(int i=0; i