79 Word Search
https://leetcode.com/problems/word-search/#/description
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
.
分析和代码
public boolean exist(char[][] board, String word) {
if(board.length == 0 || board[0].length == 0 || word == null) {
return false;
}
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(search(board, word, 0, i, j)) {
return true;
}
}
}
return false;
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private boolean search(char[][] board, String word, int index, int row, int col) {
if(index == word.length()) {
return true;
}
if(row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] == '#' || board[row][col] != word.charAt(index)) {
return false;
}
board[row][col] = '#';
for(int i = 0; i < 4; i++) {
int nextRow = dirs[i][0] + row;
int nextCol = dirs[i][1] + col;
if(search(board, word, index + 1, nextRow, nextCol)) {
return true;
}
}
board[row][col] = word.charAt(index);
return false;
}
超暴力
O(4^n)