problem link:https://leetcode.com/problems/island-perimeter/
code1:效率较高的两种解法,打败一半的人
//查看右边和下边的邻居
public class Solution {
public int islandPerimeter(int[][] grid) {
int islands = 0, neighbours = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
islands++; // count islands
if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours
if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours
}
}
}
return islands * 4 - neighbours * 2;
}
}
//与上面解法思想上是一样的,只是考虑的是左边和上边的邻居
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int result = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
result += 4;
if (i > 0 && grid[i-1][j] == 1) result -= 2;
if (j > 0 && grid[i][j-1] == 1) result -= 2;
}
}
}
return result;
}
code2:效率非常低的一种解法:直接遍历数
public class Solution {
public int islandPerimeter(int[][] grid) {
int rowLen = grid.length;
int colLen = grid[0].length;
int res = 0;
for (int i = 0; i < rowLen - 1; i++) {
for (int j = 0; j < colLen - 1; j++) {
// res += (grid[i][j] ^ grid[i][j + 1] + grid[i][j] ^ grid[i +
// 1][j]);
//这样会有错误!
res += grid[i][j] ^ grid[i][j + 1];
res += grid[i][j] ^ grid[i + 1][j];
}
}
for (int i = 0; i < rowLen; i++) {
res += grid[i][0] ^ 0;
res += grid[i][colLen - 1] ^ 0;
if (i != (rowLen - 1))
res += grid[i][colLen - 1] ^ grid[i + 1][colLen - 1];
}
for (int i = 0; i < colLen; i++) {
res += grid[0][i] ^ 0;
res += grid[rowLen - 1][i] ^ 0;
if (i != (colLen - 1))
res += grid[rowLen - 1][i] ^ grid[rowLen - 1][i + 1];
}
return res;
}
}