Java solution use XOR


  • 0
    C
    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; 
        }

  • 0
    L

    can you give some explanation?


  • 0
    C

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


  • 0
    B

    wrong answer when grid[0][0] == 1. I think code below should work:

     if (i == 0) {
        perimeter += grid[i][j] ^ 0;
     }
    if (j == 0) {
        perimeter += grid[i][j] ^ 0;
    }
    

  • 0
    C

    @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.


Log in to reply
 

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