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
|
var exist = function(board, word) { const init2DArr = (x,y,initFun)=>{ const res = [] for(let i = 0;i < y;i++) { const arr = [] for(let j = 0;j < x;j++) arr.push(initFun(x,y)) res.push(arr) } return res } const [by,bx] = [board.length,board[0].length] const vis = init2DArr(bx,by,()=>false) const dirs = [[1,0],[0,1],[-1,0],[0,-1]] const lenWord = word.length let flag = false const search = (x,y,pos)=>{ if(board[y][x].charCodeAt(0)!==word.charCodeAt(pos)) return false if(pos===lenWord-1) { flag = true return } for(let i = 0;i < 4;i++) { const [nx,ny] = [x+dirs[i][0],y+dirs[i][1]] if(nx >= 0 && ny >= 0 && nx < bx && ny < by && vis[ny][nx] === false){ console.log([nx,ny],[bx,by],vis[ny][nx]) vis[ny][nx] = true search(nx,ny,pos+1) vis[ny][nx] = false } if(flag) break } return false } for(let i = 0;i < by;i++) { for(let j = 0;j < bx;j++){ vis[i][j] = true search(j,i,0) vis[i][j] = false } } return flag };
|