public int islandPerimeter(int[][] grid) {
int perimeter = 0;
for (int i = 0; i < grid.length; i++) {
int[] line = grid[i];
for (int j = 0; j < line.length; j++) {
if (i == 0) {
perimeter += grid[i][j] ^ 0;
}
if (i == grid.length  1) {
perimeter += grid[i][j] ^ 0;
}
else {
perimeter += grid[i][j] ^ grid[i + 1][j];
}
if (j == 0) {
perimeter += grid[i][j] ^ 0;
}
if (j == line.length  1) {
perimeter += grid[i][j] ^ 0;
}
else {
perimeter += grid[i][j] ^ grid[i][j + 1];
}
}
}
return perimeter;
}
Java solution use XOR


@longshi every num just compare with it's right and top, if not same, means the perimeter + 1.

@bubbleprawn I'm sorry, my submission is just the same as you said, but I merged the 'if (i ==0 )' and 'if (j == 0)' with lack of thinking.