首頁 >web前端 >js教程 >javascript二維數組的面試題

javascript二維數組的面試題

小云云
小云云原創
2018-02-02 14:18:472371瀏覽

本文主要跟大家分享一個關於javascript二維陣列的面試題,希望能幫助大家。給定一個二維數組,實現一個功能函數fn,向這個函數中傳遞這個二維數組的一個坐標,如果這個坐標的值為”1“,將返回和這個坐標所有相連的並且坐標值為1坐標。

例如,傳遞了fn([3,4])所得到的結果為:
[[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],
] ;

解答想法:寬度優先遍歷即可。供參考,相連條件沒給出且當做是橫豎方向:

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]))
                              
出隊列進行新一輪的匹配所以只要再用一個緩存隊列存儲過往匹配的成功數據即可,沒有必要最後在進行遍歷的必要。程式碼如下:

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;
}

相關推薦:


定義JavaScript二維陣列採用定義陣列的陣列來實現_基礎知識

JavaScript二維陣列實作的省市聯動選單_javascript技巧

javascript二維陣列轉置實例_javascript技巧

#

以上是javascript二維數組的面試題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn