小明站在一个数字迷宫里,若其身边上、下、左、右四个相邻位置存在2个及以上的偶数,则小明认为其所站位置是一个幸运位置。给你一个数字迷宫(所有数字都是自然数),请你输出该迷宫的幸运位置,行号小的优先输出,若同一行号存在多个幸运位置,则按列号小的优先。
输入格式:
首先输入一个整数T(1<=T<10),表示测试组数。 每组测试首先在一行上输入两个整数m,n(2<m,n<21);然后输入一个的数字迷宫,包含m行n列的数字,每行数字之间以一个空格分隔。
输出格式:
对于每组测试,若不存在幸运位置,则输出“none”;否则,在一行上以“(r,c)”的格式输出各个幸运位置,其中r表示行号(从1开始),c表示列号(从1开始);每两个幸运位置之间间隔一个空格。引号不必输出。
输入样例:
2
3 4
85 34 67 11
11 38 67 76
34 11 25 31
3 3
85 79 93
31 91 85
31 90 85
输出样例:
(2,1) (2,3) (3,2)
none
知识点:
- multimap<int,int> mp,用来存放键(key)相同的键值对
- 向multimap 中添加数据 mp.insert(pair<int,int>(key,value))。
- 格式问题:迭代且末尾的前一个mp.end()–。
思路:
- 暴力法遍历每一个元素判断其上下左右是否为偶数。
自我纠正:
- 刚开始想的是用dfs进行深度优先遍历,但是发现对于四个边角问题的判断过于重复繁琐。于是就对其分来判断(即判断向上如果符合条件count++,向下如果符合条件count++,向左如果符合条件count++,向右如果符合条件count++。。。对就是分开判断,四个方向全部分开来单独判断)
源码:
#include<bits/stdc++.h>
using namespace std;
int room[101][101];
int m, n;
int juddge(int x, int y) {
int count = 0;
if (x + 1 <= m && room[x + 1][y] % 2 == 0)
count++;
if (x - 1 >= 1 && room[x - 1][y] % 2 == 0)
count++;
if (y + 1 <= n && room[x][y + 1] % 2 == 0)
count++;
if (y - 1 >= 1 && room[x][y - 1] % 2 == 0)
count++;
if (count >= 2)
return 1;
return 0;
}
int main() {
int t;
cin >> t;
while (t) {
multimap<int, int> mp;
cin >> m >> n;
for (int i = 1;i <= m;i++) {
for (int j = 1;j <= n;j++) {
cin >> room[i][j];
}
}
for (int i = 1;i <= m;i++) {
for (int j = 1;j <= n;j++) {
if (juddge(i, j)) {
mp.insert(pair<int,int>(i, j));
}
}
}
if (mp.empty()) {
cout << "none" << endl;
}
else {
multimap<int, int>::iterator it;
for (it = mp.begin();it != mp.end();it++) {
if(it!=(--mp.end()))
printf("(%d,%d) ",it->first, it->second);
else
printf("(%d,%d)", it->first, it->second);
}
printf("\n");
}
t--;
}
}