|
| 1 | +// 시간복잡도: O(n^2 * 4^m) |
| 2 | +// 공간복잡도: O(n * m) |
| 3 | +// (n: board의 행의 개수, m: word의 길이) |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import "testing" |
| 8 | + |
| 9 | +func TestExist(t *testing.T) { |
| 10 | + board := [][]byte{ |
| 11 | + {'A', 'B', 'C', 'E'}, |
| 12 | + {'S', 'F', 'C', 'S'}, |
| 13 | + {'A', 'D', 'E', 'E'}, |
| 14 | + } |
| 15 | + |
| 16 | + if !exist(board, "ABCCED") { |
| 17 | + t.Error("Test case 0 failed") |
| 18 | + } |
| 19 | + |
| 20 | + if !exist(board, "SEE") { |
| 21 | + t.Error("Test case 1 failed") |
| 22 | + } |
| 23 | + |
| 24 | + if exist(board, "ABCB") { |
| 25 | + t.Error("Test case 2 failed") |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +func backtrack(board [][]byte, histories [][]bool, n_row int, n_col int, word string, idx int) bool { |
| 30 | + if idx == len(word) { |
| 31 | + return true |
| 32 | + } |
| 33 | + |
| 34 | + if n_row < 0 || n_row >= len(board) { |
| 35 | + return false |
| 36 | + } |
| 37 | + |
| 38 | + if n_col < 0 || n_col >= len(board[0]) { |
| 39 | + return false |
| 40 | + } |
| 41 | + |
| 42 | + if board[n_row][n_col] != word[idx] || histories[n_row][n_col] { |
| 43 | + return false |
| 44 | + } |
| 45 | + |
| 46 | + steps := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} |
| 47 | + |
| 48 | + histories[n_row][n_col] = true |
| 49 | + |
| 50 | + for _, step := range steps { |
| 51 | + if backtrack(board, histories, n_row+step[0], n_col+step[1], word, idx+1) { |
| 52 | + return true |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + histories[n_row][n_col] = false |
| 57 | + return false |
| 58 | +} |
| 59 | + |
| 60 | +func exist(board [][]byte, word string) bool { |
| 61 | + n_rows := len(board) |
| 62 | + n_cols := len(board[0]) |
| 63 | + |
| 64 | + histories := make([][]bool, n_rows) |
| 65 | + |
| 66 | + for n_row := 0; n_row < n_rows; n_row++ { |
| 67 | + for n_col := 0; n_col < n_cols; n_col++ { |
| 68 | + if board[n_row][n_col] == word[0] { |
| 69 | + for k := 0; k < n_rows; k++ { |
| 70 | + histories[k] = make([]bool, n_cols) |
| 71 | + } |
| 72 | + |
| 73 | + if backtrack(board, histories, n_row, n_col, word, 0) { |
| 74 | + return true |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return false |
| 81 | +} |
0 commit comments