九度链接:http://ac.jobdu.com/problem.php?pid=1384
题目1384:二维数组中的查找
题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
输入: 输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为两个整数m和n(1<=m,n<=1000):代表将要输入的矩阵的行数和列数。
输入的第二行包括一个整数t(1<=t<=1000000):代表要查找的数字。
接下来的m行,每行有n个数,代表题目所给出的m行n列的矩阵(矩阵如题目描述所示,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
输出: 对应每个测试案例,
输出”Yes”代表在二维数组中找到了数字t。
输出”No”代表在二维数组中没有找到数字t。
样例输入:
3 3
5
1 2 3
4 5 6
7 8 9
3 3
1
2 3 4
5 6 7
8 9 10
3 3
12
2 3 4
5 6 7
8 9 10
样例输出:
Yes
No
No
-
答疑:
- 解题遇到问题?分享解题心得?讨论本题请访问: http://t.jobdu.com/thread-8107-1-1.html
对于二维数组的查找问题,尽可能转化为一维数组的查找问题。我们可以根据二维数组的行号和列号计算出相对于数组首地址的偏移量,从而找到对应的元素。
以二维数组右上角元素作为突破口。
//题目1384:二维数组中的查找
//AC
#include <stdio.h>
int matrix[1000000];
bool find(int* matrix, int rows, int columns, int num) {
bool found = false;
if (matrix != NULL && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (matrix[row * columns + column] == num){
found = true;
break;
}
else if (matrix[row * columns + column] > num)
column --;
else
row ++;
}
}
return found;
}
int main() {
int row, colum;
while (scanf("%d %d", &row, &colum) != EOF) {
int num;
scanf ("%d", &num);
int n = row * colum;
for (int i = 0; i < n; i ++)
scanf ("%d", &matrix[i]);
bool result = find(matrix, row, colum, num);
if (result)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}