Leetcode 463 Solution

This article provides solution to leetcode question 463 (island-perimeter)

https://leetcode.com/problems/island-perimeter

Solution

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m = grid.size();
        if (m == 0)
            return 0;

        int n = grid[0].size();
        int s = 0;

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j])
                {
                    if (i == 0 || grid[i - 1][j] == 0)
                        s++;

                    if (i == m - 1 || grid[i + 1][j] == 0)
                        s++;

                    if (j == 0 || grid[i][j - 1] == 0)
                        s++;

                    if (j == n - 1 || grid[i][j + 1] == 0)
                        s++;
                }
            }
        }

        return s;
    }
};