LeetCode 463: Island Perimeter Solution
Master LeetCode problem 463 (Island Perimeter), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
463. Island Perimeter
Problem Explanation
Explanation
To solve this problem, we can iterate over each cell in the grid and for each land cell (where grid[i][j] == 1), we can check the adjacent cells to determine the perimeter contribution of that cell. We can count the number of adjacent water cells and add that to the perimeter. The final perimeter will be the sum of all individual cell contributions.
We can iterate through the grid and for each land cell, check its adjacent cells (up, down, left, right) to count the number of water cells. The perimeter contribution for each land cell will be 4 minus the count of water cells around it.
Time complexity: O(row * col)
Space complexity: O(1)
Solution Code
class Solution {
public int islandPerimeter(int[][] grid) {
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 += 4;
if (i > 0 && grid[i - 1][j] == 1) perimeter--;
if (i < grid.length - 1 && grid[i + 1][j] == 1) perimeter--;
if (j > 0 && grid[i][j - 1] == 1) perimeter--;
if (j < grid[0].length - 1 && grid[i][j + 1] == 1) perimeter--;
}
}
}
return perimeter;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 463 (Island Perimeter)?
This page provides optimized solutions for LeetCode problem 463 (Island Perimeter) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 463 (Island Perimeter)?
The time complexity for LeetCode 463 (Island Perimeter) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 463 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 463 in Java, C++, or Python.