標籤:鄰居遍曆
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn‘t have "lakes" (water inside that isn‘t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don‘t exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]]Answer: 16Explanation: The perimeter is the 16 yellow stripes in the image below:
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M02/8C/9E/wKiom1hyR86g3TraAAAHzYGxJlk325.png-wh_500x0-wm_3-wmp_4-s_1369936785.png" title="island.png" alt="wKiom1hyR86g3TraAAAHzYGxJlk325.png-wh_50" />
題意:求島的周長。
給定一個二維整數的方格地圖,1代表陸地,0代表有水的地方。每個方格都是垂直或者水平串連的,沒有斜線。被水包圍的中間有一個小島(小島可能包含了很多個的陸地方格),小島裡沒有島中湖(內部的水和外部的水是連通的)。每個方格單元的邊長都是1。各個地方都是成直角的,長度寬度不超過100,判斷小島的邊長。
思路
判斷其四面是否有陸地,四面都有陸地的對周長無貢獻,兩面有陸地的貢獻周長為2,一面有陸地的貢獻周長為3,四面都沒有陸地的貢獻周長為4。。。。。。有思路,但是竟然不會寫。。。。。。。。。。。血崩,看了一會才想明白。
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M00/8C/9B/wKioL1hySKnwBr9lAAWTNR9dMh8045.jpg-wh_500x0-wm_3-wmp_4-s_283724932.jpg" title="IMG_20170108_220537.jpg" alt="wKioL1hySKnwBr9lAAWTNR9dMh8045.jpg-wh_50" />
這也是代碼if判斷這樣寫的原因。正常情況當我們遍曆到一座島的時候我們要判斷周圍四個鄰居的情況,但是當出現這四種情況時,部分鄰居越界,不用判斷,所以用||來控制,前面為真時後面就直接不看了,短路。而又不影響其他情況。
public class Solution { public int islandPerimeter(int[][] grid) { int sum=0; int m=grid.length,n=grid[0].length; for(int i=0;i<m;i++) for(int j=0;j<n;j++) if(grid[i][j]==1){ if(i==0||grid[i-1][j]==0) sum++; if(i==m-1||grid[i+1][j]==0) sum++; if(j==0||grid[i][j-1]==0) sum++; if(j==n-1||grid[i][j+1]==0) sum++; } return sum; }}
Leetcode 463. Island Perimeter JAVA語言