Day 21 문자열, 사칙연산, 시뮬레이션, 2차원배열, 수학, 배열

Day21 21단계 2023-11-10

2. 안전지대

class Solution {
    public int solution(int[][] board) {
		int answer = (board.length * board.length);

		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				if (board[i][j] == 1) {
					for(int row = i-1; row <= i+1; row++) {
						for (int col = j-1; col <= j+1; col++) {
							if (row >= 0 && row < board.length && col >= 0 && col < board[i].length)
								board[row][col] = (board[row][col] != 1) ? -1 : 1;
						}
					}
				}
			}
		}

		for (int[] i : board) {
			for (int j : i) {
				if (j == -1 || j == 1)
					answer--;
			}
		}
        return answer;
    }
}
class Solution {
    public int solution(int[][] board) {
		int answer = (board.length * board.length);

		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				if (board[i][j] == 1) {
					try {
						board[i][j + 1] = (board[i][j + 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {
						board[i][j - 1] = (board[i][j - 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {
						board[i + 1][j] = (board[i + 1][j] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {	
						board[i + 1][j + 1] = (board[i + 1][j + 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {
						board[i + 1][j - 1] = (board[i + 1][j - 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {
						board[i - 1][j] = (board[i - 1][j] != 1) ? -1 : 1;
						board[i - 1][j + 1] = (board[i - 1][j + 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
					try {
						board[i - 1][j - 1] = (board[i - 1][j - 1] != 1) ? -1 : 1;
					} catch (ArrayIndexOutOfBoundsException e) {}
				}
			}
		}

		for (int[] i : board) {
			for (int j : i) {
				if (j == -1 || j == 1)
					answer--;
			}
		}
        return answer;
    }
}