island-perimeter

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();

    }

}

 

posted @ 2016-11-21 15:29  blcblc  阅读(714)  评论(0编辑  收藏  举报