Bug report (or did I do something wrong... Javascript )


  • 0
    C
    var r = [];
    var roots = [];
    var conn = function(i, j, i2, j2){
    	if (r[i][j].root.getRoot().val !== r[i2][j2].getRoot().val) {
    		roots.splice(roots.indexOf(r[i][j].root.getRoot().val), 1)
    		r[i][j].root.root = r[i2][j2].getRoot();
    	}
    };
    var open = function(i, j){
    	if (i > 0 && isOpen(i-1, j)) conn(i,j,i-1,j)
    	if (j > 0 && isOpen(i, j-1)) conn(i,j,i,j-1)
    }
    var isOpen = function(i, j){
    	return r[i][j].getRoot().val > -1
    };
    function node(val, sea){
    	this.val = val;
    	this.root = sea;
    	this.getRoot = function(){
    		if (!this.root) return this;
    		if (this.root.val === this.val) return this;
    		else return this.root.getRoot()
    	}
    	if (!sea && val > -1) {
    		roots.push(val)
    		this.root = this
    	}
    }
    var sea = new node(-1);
    
    var numIslands = function(grid) {
    	if (grid.length === 1 && grid[0].length === 1) return ~~grid[0][0]
        for (var i=0; i<grid.length; i++) {
        	r[i] = []
        	for (var j=0; j<grid[i].length; j++) {
        		var val = i*grid[i].length + j;
        		if (~~grid[i][j]) {
        			r[i][j] = new node(val, null)
        			open(i, j);
        		} else {
        			r[i][j] = new node(val, sea)
        		}
        	}
        }
        return roots.length;
    };
    

    this code is working for custom test cases. but not for actual tests.
    tried ["0"] and ["11"] but customer test and actual test gives different results.


Log in to reply
 

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