-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckWordExistInGrid.js
More file actions
61 lines (49 loc) · 1.77 KB
/
Copy pathcheckWordExistInGrid.js
File metadata and controls
61 lines (49 loc) · 1.77 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Requirement : Take grid of m * n Find if word exist in grid.
*/
const exist = function(board, word) {
let rows = board.length
let cols = board[0].length
/** check if word length greater than board */
if(word.length > (rows * cols) ) return false
for(let i = 0; i < rows; i++) {
for(let j = 0; j < cols; j++) {
/** if letter found check its adjacent nodes */
if(board[i][j] === word[0]) {
let exist_flag = check_adjacent_nodes(i, j, word, board, 0, rows, cols)
if(exist_flag) return true
}
}
}
return false
}
const check_adjacent_nodes = (row, col, word, board, level, maxRows, maxCol) => {
let l = word.length;
// Pattern matched
if (level == l)
return true;
// Out of Boundary
if (row < 0 || col < 0 || row >= maxRows || col >= maxCol)
return false;
if(board[row][col] === word[level]) {
let tmp = board[row][col]
board[row][col] = '#'
let res =
/** check top */
check_adjacent_nodes(row - 1, col, word, board, level + 1, maxRows, maxCol) ||
/** check bottom */
check_adjacent_nodes(row + 1, col, word, board, level + 1, maxRows, maxCol) ||
/** check left */
check_adjacent_nodes(row, col - 1, word, board, level + 1, maxRows, maxCol) ||
/** check right */
check_adjacent_nodes(row, col + 1, word, board, level + 1, maxRows, maxCol)
board[row][col] = tmp
return res
} else {
return false
}
}
let board = [['A', 'B', 'C', 'E'],['S', 'F', 'C', 'S'], ['A','D','E', 'E']]
let word = 'ABCESEEC'
let result = exist(board, word)
console.log(result)