Array_3시, 6시, 9시 12시 방향보다 큰 숫자
✅ 숫자 격자판이 주어졌을 때 나의 앞, 뒤, 양 옆 숫자들보다 크면 봉우리. 봉우리는 몇 개 인가요?
격자판의 가장자리는 0으로 초기화되어 있습니다. 만약 N=5라면, 격자판은 다음과 같이 생겼습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Main {
int[] dx= {-1, 0, 1, 0};
int[] dy= {0, 1, 0, -1};
public int solution(int n, int[][] intArr){
int answer=0;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
boolean flag= true;
for(int k=0; k<dx.length; k++){
int nx= i + dx[k];
int ny= j + dy[k];
if(nx>=0 && nx<n && ny>=0 && ny<n && intArr[i][j] <= intArr[nx][ny]) {
flag= false;
break;
}
}
if(flag) answer++;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
int[][] intArr = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
intArr[i][j]= sc.nextInt();
}
}
System.out.print(T.solution(n, intArr));
}
}
//⭐️input:
// 5
// 5 3 7 2 3
// 3 7 1 6 1
// 7 2 5 3 4
// 4 3 6 4 1
// 8 7 3 5 2
//⭐️output:
//10
🔵 ThingsILearned
✔️ 방향 설정하기
- 시계 방향으로 돌면 x는 -1, 0, +1, 0 순이고, y는 0, +1, 0, -1 순이다.
- 3중 for문, 마지막 for문에서 k는 방향 배열을 돈다.
- 방향 배열을 돌면서 intArr 인덱스 값에 -1, 0, 1을 더해 시계방향으로 intArr 인덱스가 돌도록 한다.
- 그런데 이 때 intArr 배열을 벗어나면 안되니까 인덱스가 0보다 크게, 그리고 n을 벗어나지 않도록 조건을 준다.
🟢 새로운 배열 만들기, 2중 for문, <앞, 뒤, 왼쪽, 오른쪽>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Main {
public int solution(int n, int[][] intArr){
int answer=0;
for(int i=1; i<n+1; i++){
for(int j=1; j<n+1; j++){
if(intArr[i][j]> intArr[i-1][j] && intArr[i][j]> intArr[i][j-1]&& intArr[i][j]> intArr[i+1][j] && intArr[i][j]> intArr[i][j+1]){ //<앞, 뒤, 왼쪽, 오른쪽>
answer++;
}
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
int[][] intArr = new int[n+2][n+2]; //가장가리가 0으로 초기화되어있는 배열 만들기
for(int i=1; i<n+1; i++){
for(int j=1; j<n+1; j++){
intArr[i][j]= sc.nextInt();
}
}
System.out.print(T.solution(n, intArr));
}
}
This post is licensed under CC BY 4.0 by the author.