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:
用一个二位数组表示一个地图,1表示陆地,0表示海水,求由1组成的区域的边长
static public int IslandPerimeter(int[,] grid) {
int num = 0;
int rowNum = grid.GetLength(0) - 1;
int colNum = grid.GetLength(1) - 1;
for (int row = 0; row <= rowNum; row++) {
for (int col = 0; col <= colNum; col++) {
if (grid[row, col] != 1) continue;
if (row == 0) {
num++;
}
if (row == rowNum) {
num++;
}
if (col == 0) {
num++;
}
if (col == colNum) {
num++;
}
if (col - 1 >= 0 && grid[row, col - 1] == 0) {
num++;
}
if (col + 1 <= colNum && grid[row, col + 1] == 0) {
num++;
}
if (row - 1 >= 0 && grid[row - 1, col] == 0) {
num++;
}
if (row + 1 <= rowNum && grid[row + 1, col] == 0) {
num++;
}
}
}
return num;
}
原文:http://www.cnblogs.com/xiejunzhao/p/0f335555ce85efdf3c761d7e743db189.html