463. Island Perimeter - LeetCode
阿新 • • 發佈:2018-07-02
alt left continue i+1 一是 思路 ava for 就是
Question
463. Island Perimeter
Solution
題目大意:給出一個二維數組1表示陸地0表示海,求陸地的周長
思路:
重新構造一張地圖grid2即一個二維數組,比原數組大一圈,即長寬都大2
一個點在原地圖坐標是(i,j),那麽在重新構造的坐標就是(i+1,j+1)
遍歷原地圖,如果一是陸地,就遍歷這個點的周圍是否是海,如果是海線周長就加1
Java實現:
public int islandPerimeter(int[][] grid) { int total = 0; int[][] grid2 = new int[grid.length+2][grid[0].length+2]; for (int i=0; i<grid.length; i++) { for (int j=0; j<grid[0].length; j++) { if (grid[i][j] == 1) { grid2[i+1][j+1] = 1; } } } for (int i=0; i<grid.length; i++) { for (int j=0; j<grid[i].length; j++) { int x = i+1; int y = j+1; if (grid2[x][y] == 0) continue; // left total += grid2[x-1][y]==1?0:1; // right total += grid2[x+1][y]==1?0:1; // top total += grid2[x][y-1]==1?0:1; // bottom total += grid2[x][y+1]==1?0:1; } } return total; }
463. Island Perimeter - LeetCode