目录
- 问题描述
- 输入格式
- 输出格式
- 代码实现
问题描述
小蓝拥有n × n大小的棋盘,一开始棋盘上全都是白子。小蓝进行了m.次操作,每次操作会将棋盘上某个范围内的所有棋子的颜色取反(也就是白色棋子变为黑色,黑色棋子变为白色)。请输出所有操作做完后棋盘上每个棋子的颜色。
输入格式
输入的第一行包含两个整数n,m,用一个空格分隔,表示棋盘大小与操作数。
接下来m行每行包含四个整数x1,y1,x2,y2,相邻整数之间使用一个空格分隔,表示将在x1至x2行和y1至y2列中的棋子颜色取反。
3 3
1 1 2 2
2 2 3 3
1 1 3 3
输出格式
输出n行,每行n个0或1表示该位置棋子的颜色。如果是白色则输出0,否则输出1。
001
010
100
代码实现
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
// 在此输入您的代码...
int n = scan.nextInt();// 棋盘大小
int m = scan.nextInt();// 操作数
int[][] arr = new int[n][n];// 创建二维数组存储棋子
// 循环输入指令
for (int i = 0; i < m; i++) {
// 取反两个坐标之间的区域
int x1 = scan.nextInt();
int y1 = scan.nextInt();
int x2 = scan.nextInt();
int y2 = scan.nextInt();
// 调用反转函数
reverse(arr, x1, y1, x2, y2);
}
// 打印棋盘内容
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();// 每打印一行插入换行符
}
scan.close();
}
// 二维数组元素取反函数
public static void reverse(int[][] arr, int x1, int y1, int x2, int y2) {
// x1到x2之间,y1到y2之间的元素取反
for (int i = x1 - 1; i <= x2 - 1; i++) {
for (int j = y1 - 1; j <= y2 - 1; j++) {
if (arr[i][j] == 1) {
// 1变0
arr[i][j] = 0;
} else {
// 0变1
arr[i][j] = 1;
}
}
}
}
}