Skip to content

Commit e513a1f

Browse files
committed
Added Island Perimeter
1 parent 3a42d15 commit e513a1f

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

src/island_perimeter.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/// You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and
2+
/// `grid[i][j] = 0` represents water.
3+
///
4+
/// Grid cells are connected horizontall/vertically (not diagonally). The `grid` is completely
5+
/// surrounded by water, and there is exactly one island (e.g., one or more connected land cells).
6+
///
7+
/// The island doesn't have "lakes", meaning the water inside isn't connected to the water around
8+
/// the island. One cell is a square with side length 1. The grid is rectangular, width and height
9+
/// don't exceed 100. Determine the perimeter of the island.
10+
struct Solution;
11+
12+
impl Solution {
13+
14+
pub fn island_perimeter(grid: Vec<Vec<i32>>) -> i32 {
15+
let m = grid.len();
16+
let n = grid[0].len();
17+
18+
let mut result = 0;
19+
20+
for i in 0..m {
21+
for j in 0..n {
22+
if grid[i][j] == 1 {
23+
// above
24+
let above = if i == 0 { 0 } else { grid[i-1][j] };
25+
26+
// below
27+
let below = if i == m-1 { 0 } else { grid[i+1][j] };
28+
29+
// left
30+
let left = if j == 0 { 0 } else { grid[i][j-1] };
31+
32+
// right
33+
let right = if j == n-1 { 0 } else { grid[i][j+1] };
34+
35+
let count = above + below + left + right;
36+
let sides = 4 - count;
37+
result += sides;
38+
}
39+
}
40+
}
41+
42+
result
43+
}
44+
45+
}
46+
47+
#[cfg(test)]
48+
mod tests {
49+
use super::Solution;
50+
51+
#[test]
52+
fn example_1() {
53+
let grid = vec![
54+
vec![0,1,0,0],
55+
vec![1,1,1,0],
56+
vec![0,1,0,0],
57+
vec![1,1,0,0],
58+
];
59+
let result = Solution::island_perimeter(grid);
60+
assert_eq!(result, 16);
61+
}
62+
63+
#[test]
64+
fn example_2() {
65+
let grid = vec![
66+
vec![1],
67+
];
68+
let result = Solution::island_perimeter(grid);
69+
assert_eq!(result, 4);
70+
}
71+
72+
#[test]
73+
fn example_3() {
74+
let grid = vec![
75+
vec![1, 0],
76+
];
77+
let result = Solution::island_perimeter(grid);
78+
assert_eq!(result, 4);
79+
}
80+
81+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,8 @@ pub mod repeated_substring_pattern; // 459 ✓
414414

415415
pub mod hamming_distance; // 461 ✓
416416

417+
pub mod island_perimeter; // 463
418+
417419
pub mod ones_and_zeroes; // 474
418420

419421
pub mod sliding_window_median; // 480 ✓

0 commit comments

Comments
 (0)