Leetcode 463. Island Perimeter JAVA語言

來源:互聯網
上載者:User

標籤:鄰居遍曆

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語言

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.