leetcode笔记:37. sudoku solver

# Title Difficulty Topic
37 Sudoku Solver Hard Hash Table; Backtracking

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.

Example:

1
2
3
4
5
6
7
8
9
10
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Backtracking

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
class  {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 ||
board[0] == null || board[0].length == 0) return false;
char[] words = word.toCharArray();
int m = board.length, n = board[0].length;
if(m * n < words.length) return false;

for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(helper(board, i, j, words, 0)) return true;
}
}
return false;
}

public boolean helper(char[][] board, int i, int j, char[] words, int start) {
if(start == words.length) return true;
if(i >= board.length || i < 0 ||
j >= board[0].length || j < 0) return false;
if(board[i][j] != words[start]) return false;

boolean exist = false;
board[i][j] += 128;
if(helper(board, i-1, j, words, start+1) ||
helper(board, i+1, j, words, start+1) ||
helper(board, i, j-1, words, start+1) ||
helper(board, i, j+1, words, start+1)) exist = true;
board[i][j] -= 128; // board[i][j] &= 127;
return exist;
}
}

时间复杂度为$$O(mn 4^L)$$,空间复杂度$$O(L)$$,$$L$$为word的长度。