-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.js
84 lines (66 loc) · 2.24 KB
/
DFS.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
let allBoxes = document.querySelectorAll('.box')
let startBoxNo = null
let endBoxNo = null
allBoxes.forEach((box,boxNo)=>{
if(box.innerHTML=='I'){startBoxNo = boxNo}
else if(box.innerHTML=='G'){endBoxNo = boxNo}
//box.innerHTML += boxNo
})
let startState = Result('no state needed',startBoxNo)
let endState = Result('no state needed',endBoxNo)
//Algorithm starts here
let state = {marginLeft:`${startState.marginLeft}`, marginTop:`${startState.marginTop}`}
let parentNode = null
let parentAction = null
let firstNode = {state:state, parentAction:parentAction, parentNode:parentNode}
let frontier = []
let explored = []
let goalState = false
let frontierLen = true
frontier.push(firstNode)
while(!goalState){
if(!frontier.length){frontierLen = false; break}
goalState = checkGoalState(frontier[frontier.length-1].state,endState)
if(goalState){break}
let possibleBoxNos = Actions(frontier[frontier.length-1].state)
let temp = []
possibleBoxNos.forEach((boxNo)=>{
let state = Result('no state needed',boxNo)
let parentAction = boxNo
let parentNode = frontier[frontier.length-1]
let node = {state:state, parentAction:parentAction, parentNode:parentNode}
let alreadyDone = false
let combinedArr = frontier.concat(explored)
combinedArr.forEach((cnode)=>{
if(cnode.state.marginLeft==node.state.marginLeft && cnode.state.marginTop==node.state.marginTop){
alreadyDone = true
}
})
if(!alreadyDone){
temp.push(node)
}
})
explored.push(frontier[frontier.length-1])
frontier.pop()
temp.forEach((node)=>{
frontier.push(node)
})
}
if(frontierLen){
let cellsArr = []
let actionsArr = []
let State = frontier[frontier.length-1].state
let Node = frontier[frontier.length-1]
while(State != state){
cellsArr.push(Node.state)
actionsArr.push(Node.parentAction)
Node = Node.parentNode
State = Node.state
}
cellsArr.reverse()
actionsArr.reverse()
show=='S' ? showSol(actionsArr) : showExp()
}
else{
alert('No solution possible!')
}