Recursive solution. In DFS like approach


  • 1
    P

    Basically, what I do is find the first land. And then recursively go to the other neighbouring land in DFS like fashion while updating the count

    var visit = function(matrix, visited, i, j, total) {
        var count = 0;
        var x = [1,0,0,-1]
        var y = [0,1,-1,0]
        for(var m = 0; m<x.length; m++){
            if(isValid(matrix, visited, i+x[m], j+y[m])) {
                count++;
                if(!visited[i+x[m]][j+y[m]]) { //unvisted land
                    visited[i+x[m]][j+y[m]]=true;
                    visit(matrix, visited, i+x[m], j+y[m],total)
                }
            }
        }
        total.val = total.val + 4 - count;
    }
    
    var isValid = function(matrix,visited, i,j) {
        if(i<0 || j<0 || i>=matrix.length || j>=matrix[0].length || !matrix[i][j]) return false;
        return true;
    }
    
    /**
     * @param {number[][]} grid
     * @return {number}
     */
    var islandPerimeter = function(matrix) {
        var visited = [];
        var set = false;
        var si;
        var sj;
        for(var i = 0; i<matrix.length; i++) {
            visited[i] = [];
             for(var j = 0; j<matrix[0].length; j++){
                 visited[i][j]=false;
                 if(!set && matrix[i][j]) {
                     set = true;
                     visited[i][j]=true;
                     si=i;
                     sj=j;
                 }
             }
        }
        var total = {
            val: 0
        }
        visit(matrix, visited, si, sj, total)
        return total.val
        
    };
    

Log in to reply
 

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