This article mainly shares with you an interview question about javascript two-dimensional arrays. I hope it can help you. Given a two-dimensional array, implement a functional function fn and pass a coordinate of the two-dimensional array to this function. If the value of this coordinate is "1", all coordinates connected to this coordinate and whose coordinate value is 1 will be returned. .
For example, passing fn([3,4]) results in:
[[3,4],[4,4],[5,4],[6,4] ,[7,4],[8,4],[8,5],[8,6]]
var arr =[
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
] ;
Solution idea: Just traverse width first. For reference, the connection conditions are not given and are regarded as horizontal and vertical directions:
var arr =[
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
]
function fn ([x, y]) {
if (arr[x][y] !== 1) return false
const queue = [[x, y]]
const memo = arr.map(row => new Array(row.length).fill(false))
const direction = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
]
while(queue.length > 0) {
const [x, y] = queue.pop()
direction.forEach(([h, v]) => {
const newX = x + h
const newY = y + v
if (arr[newX][newY] === 1 && !memo[newX][newY]) {
memo[newX][newY] = true
queue.push([newX, newY])
}
})
}
const result = []
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if(memo[i][j]) {
result.push([i, j])
}
}
}
return result
}
console.log(fn([3,4]))
Dequeue for a new round of matching, so you only need to use another cache queue to store the successful data of past matching. There is no need to traverse at the end. The code is as follows: var arr =[
function fn(point) {
var memo = {}, result = [], direction = [[-1, 0],[1, 0],[0, -1],[0, 1]]
function dg([x, y]) {
result.push(memo[x + "," + y] = [x, y]);
direction.forEach(([h, v]) => {
const newX = x + h
const newY = y + v
if (arr[newX][newY] === 1 && !memo[newX + "," + newY]) {
dg([newX, newY]);
}
})
}
dg(point);
return result;
}
Related recommendations:
Defining a JavaScript two-dimensional array is implemented using an array of defined arrays _Basic knowledge
Province and city linkage menu implemented by JavaScript two-dimensional array_javascript skills
javascript two-dimensional array transposition example_javascript skills
The above is the detailed content of Javascript two-dimensional array interview questions. For more information, please follow other related articles on the PHP Chinese website!