1 minute read

Cavity Map (Hacker Rank)

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 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.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        char[][] grid = new char[n][n];
        for(int grid_i=0; grid_i < n; grid_i++){
            String spaces = in.next();
            grid[grid_i] = spaces.toCharArray();
        }
        for(int i=0; i < n; i++){
            for(int j=0; j < n; j++){
                if(i > 0 && i < n-1 && j > 0 && j < n-1){
                    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]){
                        System.out.print('X');
                    }else{
                        System.out.print(grid[i][j]);
                    }
                }else{
                    System.out.print(grid[i][j]);
                }
            }
            System.out.println();
        }
    }
}


행운의 77문제 프로젝트
  행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.
  (한달은 이미 많이 지났지만...그래도 77문제는 될 수 있도록!)