C++ Solution easy and fast O(mn) Complexity


  • 0
    S
    int islandPerimeter(vector<vector<int>>& grid){
    	int result = 0;
    	int length = grid.size();
    	int width = grid[0].size();
    	for (int i = 0; i<length; i++){
    		for (int j = 0; j<width; j++){
    			if (grid[i][j] == 1)
    			{
    				result += 4;
    				if (i > 0)
    					if (grid[i - 1][j] == 1)
    						result = result - 1;
    					if (i < length - 1)
    						if (grid[i + 1][j] == 1)
    							result = result - 1;
    					if (j > 0)
    						if (grid[i ][j-1] == 1)
    							result = result - 1;
    					if (j < width - 1)
    						if (grid[i ][j+1] == 1)
    							result = result - 1;
    				}
    			}
    		}
    	return result;
    }

Log in to reply
 

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