Anyone past the problem with Javascript?


  • 0
    H

    Problem: https://leetcode.com/problems/surrounded-regions/

    I used the DFS solution wrote in JavaScript to run the code, but with runtime error result in a very big matrix example, I examed my codes and thought if it's the problem of JavScript's internal consuming longer than other language, to cause the problem? Anyone past the problem with JavaScript, thanks. Here's my code.

    let solve = function(board) {
        if (board.length === 0) {
            return ;
        }
        
        let rowlen = board.length,
            collen = board[0].length,
            rowecp = rowlen-1,
            colecp = collen-1;
            
        for (let i=0; i<collen; i++) {
            // 判断第一行是否存在'O'
            judZero(0, i, rowlen, collen, board);
            
            // 判断最后一行是否存在'O'
            judZero(rowecp, i, rowlen, collen, board);
        }
        
        
        for (let i=1; i<rowecp; i++) {
            // 判断第一列是否存在'O'
            judZero(i, 0, rowlen, collen, board);
            
            // 判断最后一列是否存在'O'
            judZero(i, colecp, rowlen, collen, board);
        }
        
        for (let i=0; i<rowlen; i++) {
            for (let j=0; j<collen; j++) {
                if (board[i][j] === '1') {
                    board[i][j] = 'O';
                }
                if (board[i][j] === 'O') {
                    board[i][j] = 'X';
                }
            }
        }
        
        return ;
    };
    
    let judZero = function(x, y, rowlen, collen, matrix) {
        if (matrix[x][y] !== 'O') {
            return ;
        }
        
        matrix[x][y] = '1';
        
        if (x-1 >= 0) {
            judZero(x-1, y, rowlen, collen, matrix);
        }
        if (x+1 < rowlen) {
            judZero(x+1, y, rowlen, collen, matrix);
        }
        if (y-1 >= 0) {
            judZero(x, y-1, rowlen, collen, matrix);
        }
        if (y+1 < collen) {
            judZero(x, y+1, rowlen, collen, matrix);
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.