Cavity Map

You are given a square map as a matrix of integer strings. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has a strictly smaller depth. Two cells are adjacent if they have a common side or edge.

Find all the cavities on the map and replace their depths with the uppercase character X.


Example:

Input:  n=4, str[]={"1112","1912","1892","1234"}
Output: 1112
1X12
18X2
1234

Approach

Java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CavityMap {
    public static void main(String[] args) {
        String[] grid = { "1112""1912""1892""1234" };
        String[] res = cavityMap(grid);
        System.out.println(Arrays.toString(res));
    }

    static String[] cavityMap(String[] grid) {
        int n = grid.length;
        for (int i = 1; i < n - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (grid[i].charAt(j) > grid[i].charAt(j - 1) && 
                grid[i].charAt(j) > grid[i].charAt(j + 1)
                        && grid[i].charAt(j) > grid[i - 1].charAt(j)
                 && grid[i].charAt(j) > grid[i + 1].charAt(j)) {
                    char c[] = grid[i].toCharArray();
                    c[j] = 'X';
                    grid[i] = new String(c);
                }
            }
        }
        List<Stringres = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            res.add(grid[i]);
        }
        return  res.toArray(new String[0]);
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringcavityMap(vector<stringgrid)
{

    int n = grid.size();
    for (int i = 1i < n - 1i++)
    {
        for (int j = 1j < n - 1j++)
        {
            if (grid[i][j] > grid[i][j - 1] &&
                grid[i][j] > grid[i][j + 1] &&
                grid[i][j] > grid[i - 1][j] &&
                grid[i][j] > grid[i + 1][j])
            {
                grid[i][j] = 'X';
            }
        }
    }
    vector<stringres;
    for (int i = 0i < ni++)
    {
        res.push_back(grid[i]);
    }
    return res;
}
int main()
{
    int n = 4;

    vector<stringgrid = {"1112""1912""1892""1234"};
    vector<stringres = cavityMap(grid);
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i] << "\n";
    }
    return 0;
}


No comments:

Post a Comment