1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; boolean[][] mark = null;
public boolean exist(char[][] board, String word) {
if (word == null || board.length == 0) { return false; } mark = new boolean[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { mark[i][j] = true; if (exist(board, word, 1, i, j)) { return true; } mark[i][j] = false; } } } return false; }
private boolean exist(char[][] board, String word, int index, int i, int j) { if (word.length() == index) { return true; } for (int temp = 0; temp < directions.length; temp++) { int newI = i + directions[temp][0]; int newJ = j + directions[temp][1]; if (newI >= 0 && newI < board.length && newJ >= 0 && newJ < board[0].length) { if (!mark[newI][newJ] && word.charAt(index) == board[newI][newJ]) { mark[newI][newJ] = true; if (exist(board, word, index + 1, newI, newJ)) { return true; } mark[newI][newJ] = false; } } } return false; } }
|
近期评论