您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Word Search

2015-12-03 16:25 239 查看

Word Search

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.

For example,
Given board =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.

https://leetcode.com/problems/word-search/

找单词,DFS。
每一步都可以上下左右四个方向走,开一个数组visited记录已经走过的格子。

/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist2 = function(board, word) {
if(word === "") return true;
if(board.length === 0) return word === "" ? true : false;
var i, j, rowLen = board.length, colLen = board[0].length, visited = [];
for(i = 0; i < rowLen; i++)    visited[i] = [];
for(i = 0; i < board.length; i++)
for(j = 0; j < colLen; j++)
if(board[i][j] === word[0])
if(dfs(0, i, j)) return true;
return false;

function dfs(index, x, y){
if(index === word.length - 1) return true;
visited[x][y] = true;
if(dfsNeighbor(index, x - 1, y)) return true; //up
if(dfsNeighbor(index, x + 1, y)) return true; //down
if(dfsNeighbor(index, x, y - 1)) return true; //left
if(dfsNeighbor(index, x, y + 1)) return true; //right
visited[x][y] = false;
return false;
}
function dfsNeighbor(index, x, y){
if(!board[x] || !board[x][y]) return false;
if(!visited[x][y] && board[x][y] === word[index + 1]){
return dfs(index + 1, x, y);
}
return false;
}
};


优化了一下,不用开visited数组,直接用入参的board记录是否访问过。

/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
if(word === "") return true;
var i, j;
for(i = 0; i < board.length; i++)
for(j = 0; j < board[i].length; j++)
if(board[i][j] === word[0])
if(dfs(0, i, j)) return true;
return false;

function dfs(index, x, y){
if(index === word.length) return true;
if(!board[x] || !board[x][y]) return false;
if(board[x][y] !== '#' && board[x][y] === word[index]){
var ch = board[x][y];
board[x][y] = '#';
if(dfs(index + 1, x - 1, y)) return true; //up
if(dfs(index + 1, x + 1, y)) return true; //down
if(dfs(index + 1, x, y - 1)) return true; //left
if(dfs(index + 1, x, y + 1)) return true; //right
board[x][y] = ch;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: