题目大意
给你一个$n$行$m$列的矩阵($1 leqslant n leqslant 10$,$1 leqslant m leqslant 10$) ,矩阵中的一个格子最多与四个格子相连(上、下、左、右)。你每次可以给矩阵中一对相连的格子同时加上一个相同的整数,反复做这个操作,你能得到一个全零矩阵吗?
题解
其实每次相当于蛇形加数,也就是按$(1, 1)$ -> $(1, 2)$ -> ... -> $(1,m)$ -> $(2, m)$ -> $(2, m - 1)$ -> ... -> $(2,1)$ -> $(3,1)$ -> $(3,2)$ -> ...的顺序加数,每次加的都是前一次加数的位置上的数的相反数,比如$a[1][2]$加的就是$-a[1][1]$,$a[2][m]$加的是$-a[1][m]$,最后判断最后一次加数的位置上的数是否为$0$即可。
#include <iostream> using namespace std; int T; int n, m; int a[15][15]; int main() { cin >> T; while(T--) { cin >> n >> m; for(register int i = 1; i <= n; ++i) { for(register int j = 1; j <= m; ++j) { cin >> a[i][j]; } } for(register int i = 1; i <= n; ++i) { if(i & 1) { a[i][1] -= a[i - 1][1]; for(register int j = 2; j <= m; ++j) { a[i][j] -= a[i][j - 1]; } } else { a[i][m] -= a[i - 1][m]; for(register int j = m - 1; j; --j) { a[i][j] -= a[i][j + 1]; } } } if(n & 1) { if(a[n][m]) cout << "No "; else cout << "Yes "; } else { if(a[n][1]) cout << "No "; else cout << "Yes "; } } return 0; }