island-perimeter ╰+哭是因爲堅強的太久メ 2022-03-30 06:44 123阅读 0赞 https://leetcode.com/problems/island-perimeter/ package com.company; import java.util.*; class Solution { public int islandPerimeter(int[][] grid) { int ret = 0; int[] x = {-1, 0, 1, 0}; int[] y = { 0, 1, 0, -1}; for (int i=0; i<grid.length; i++) { for (int j=0; j<grid[0].length; j++) { if (grid[i][j] == 1) { for (int k=0; k<4; k++) { if (i+x[k] < 0 || i+x[k] >= grid.length || j+y[k] < 0 || j+y[k] >= grid[0].length || grid[i+x[k]][j+y[k]] == 0) { ret++; } } } } } return ret; } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: int[][] grid = { { 0,1,0,0},{ 1,1,1,0},{ 0,1,0,0},{ 1,1,0,0}}; int ret = solution.islandPerimeter(grid); System.out.printf("ret:%d\n", ret); System.out.println(); } }
还没有评论,来说两句吧...