練習
請用二維陣列輸出九九乘法表
a015: 矩陣的翻轉 https://zerojudge.tw/ShowProblem?problemid=a015
b367: 翻轉世界 https://zerojudge.tw/ShowProblem?problemid=b367
a694: 吞食天地二 https://zerojudge.tw/ShowProblem?problemid=a694
d625: 踩地雷真好玩(較困難,本堂課可以不做) https://zerojudge.tw/ShowProblem?problemid=d625
解答
a015: 矩陣的翻轉
從對角線對稱翻轉,所以把arr[i][j]填入arr[j][i]即可
#include <iostream>
using namespace std;
int main() {
int arr[100][100];
int x, y;
while (cin >> x >> y) {
for (int i= 0; i < x;i++){
for (int j= 0; j < y;j++){
cin >> arr[i][j];
}
}
for (int i= 0; i < y;i++){
for (int j= 0; j < x;j++){
cout << arr[j][i] << " ";
}
cout << endl;
}
}
return 0;
}
b367: 翻轉世界
旋轉180度,等於把整個陣列給reverse
測資解釋
範例輸入
2 <= 代表2個二維陣列
3 3 <= 第1個二維陣列是 3 X 3
1 1 0 <= 3 X 3 的二維陣列
0 1 0
0 1 1
1 5 <= 第2個二維陣列是 1 X 5
0 0 1 0 1 <= 1 X 5 的二維陣列
範例輸出
go forward <= 第1個二維陣列轉180度之後,還是長得一樣
keep defending <= 第2個二維陣列,長得不一樣
#include <iostream>
using namespace std;
int main()
{
int dataCount, row, col, arr[11][11], arr180[11][11];
cin >> dataCount;
while (dataCount--) {
cin >> row >> col;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> arr[i][j];
arr180[row - i - 1][col - j - 1] = arr[i][j];
}
}
bool flag = false;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (arr[i][j] != arr180[i][j]) {
flag = true;
break;
}
}
}
cout << (flag ? "keep defending" : "go forward") << endl;
}
return 0;
}
a694: 吞食天地二
測資解釋
3 3 <= 第一個3代表下面會有3*3的正方形,後面3那個代表正方形下面會有3行
1 2 3 <= 3*3正方形
4 5 6
7 8 9
1 1 3 3 <= 代表座標(1,1)與(3,3)圍成的正方形
1 1 1 3 <= 代表座標(1,1)與(1,3)圍成的長方形
1 1 3 1 <= 代表座標(1,1)與(3,1)圍成的長方形
#include <iostream>
using namespace std;
int main() {
int arr[500][500];
int n, m, x1[10000], y1[10000], x2[10000], y2[10000];
int sum = 0;
cin >> n >> m;
for (int i= 0; i < n;i++){
for (int j= 0; j < n;j++){
cin >> arr[i][j];
}
}
for (int i= 0; i < m;i++){
cin >> x1[i];
cin >> y1[i];
cin >> x2[i];
cin >> y2[i];
}
int eatTimes = 0;
while (eatTimes<m){
sum = 0;
for (int i= x1[eatTimes]-1; i <= x2[eatTimes]-1;i++){
for(int j= y1[eatTimes]-1; j <= y2[eatTimes]-1;j++){
sum += arr[i][j];
}
}
eatTimes++;
cout<<sum<<endl;
}
}
d625: 踩地雷真好玩
二維地圖走 八方位
#include <bits/stdc++.h>
using namespace std;
int N;
char arr[105][105];
int cnt[105][105];
int dx[]={ -1, 0, 1, -1, 1, -1, 0, 1 };
int dy[]={ -1, -1, -1 , 0 , 0 , 1 , 1 , 1 };
int main(){
cin >> N;
for ( int i = 0 ; i < N; i++ )
cin >> arr[i];
for ( int i = 0 ; i < N; i++ )
for ( int j = 0 ; j < N; j++ )
cnt[i][j] = 0;
for ( int i = 0 ; i < N; i++ )
for ( int j = 0 ; j < N; j++ )
if ( arr[i][j] == '-' ){
for ( int d = 0 ; d < 8 ; d++ ){
int nx = j + dx[d];
int ny = i + dy[d];
if ( nx < 0 || ny < 0 || nx >= N || ny >= N )
continue;
else{
if ( arr[ny][nx] == '*' )
cnt[i][j]++;
}
}
}
for ( int i = 0 ; i < N ; i++ ){
for ( int j = 0 ; j < N ; j++ ){
if ( arr[i][j] == '*' )
cout << '*';
else if ( cnt[i][j] == 0 )
cout << '-';
else
cout << cnt[i][j];
}
cout << endl;
}
return 0;
}