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: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:
我写了一大堆 然后发现自己的for循环写的太复杂了 下面有一种简便的写法
public class Solution { public int islandPerimeter(int[][] grid) { if(grid==null || grid.length==0) return 0; int perimeter = 0; int[][] dirs = {{-1,0},{1,0},{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[] dir : dirs){//这个地方使用了简便的for循环 要注意这种写法 dir是一维数组 在循环的过程中分别被赋值为
int xx = i+dir[0], yy = j+dir[1]; if(xx<0 || yy<0 || xx>=grid.length || yy>=grid[0].length || grid[xx][yy]==0) perimeter++; //border or water } } } } return perimeter; }}{-1,0},{1,0},{0,-1},{0,1}
另外这里有一个dfs的写法public int islandPerimeter(int[][] grid) { if(grid==null || grid.length==0) return 0; int perimeter = 0; for(int i=0; i<grid.length; i++){ for(int j=0; j<grid[0].length; j++){ if(grid[i][j]==1){ perimeter = dfs(i, j, grid);//这里的dfs函数就是用来计算一个小方块的边长 break; } } } return perimeter; } int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; private int dfs(int x, int y, int[][] grid){ grid[x][y] = 2;//这里巧妙用了一个flag int count = 0; for(int[] dir : dirs){ int xx = x+dir[0]; int yy = y+dir[1]; if(xx<0 || yy<0 || xx>=grid.length || yy>=grid[0].length || grid[xx][yy]==0) { count++; //border or water } else if(grid[xx][yy]==1){ // 如果上面的情况都不是 说明当前island的旁边的xx,yy是一块没有遍历的陆地,于是进入递归 count += dfs(xx, yy, grid); } } return count; }