Skip to Content
CoursesCSC122โปรแกรมเปิด/ปิดสวิตช์ไฟ

โปรแกรมเปิด/ปิดสวิตช์ไฟ

โจทย์

Giving a grid (two-dimensional array) containing lights, write a program to toggle the light according to the following conditions:

  1. User number 0 and 1 to represent light off and on respectively.
  2. At the selected position, the light will be toggled. The light in the adjacent positions are also toggled. These include the above, the below, the left and the right.

For example, giving the grid below if the selected toggle position is at row 1 and column 2, the toggle is shown as below.

0 0 1 1 1 0 *1* 1 1 0 0 0
0 0 *0* 1 1 *1* *0* *0* 1 0 *1* 0

The input has three lines. The first line indicates a size of array (i.e., rows and columns which are at least 3 rows/columns). The second line contains a list of 0 and 1 values in an array. The third line contains the toggled positions (i.e., row and column). The output is the resulted array after toggling the input array according to the toggle positions.

InputOutput
3 4
0 0 1 1 1 0 1 1 1 0 0 0
1 2
0 0 0 1 1 1 0 0 1 0 1 0

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int rows = scanner.nextInt(); int cols = scanner.nextInt(); int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = scanner.nextInt(); } } int targetRow = scanner.nextInt(); int targetCol = scanner.nextInt(); toggleLights(matrix, targetRow, targetCol); for (int[] row : matrix) { for (int value : row) { System.out.print(value + " "); } } } private static void toggleLights(int[][] matrix, int row, int col) { toggle(matrix, row - 1, col); // Top toggle(matrix, row, col - 1); // Left toggle(matrix, row, col); // Center toggle(matrix, row, col + 1); // Right toggle(matrix, row + 1, col); // Bottom } private static void toggle(int[][] matrix, int row, int col) { if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[0].length) { matrix[row][col] = 1 - matrix[row][col]; } } }

คำอธิบาย

ปรับปรุงล่าสุด