首页 > 其他 > 详细

判断数X是否在矩阵中

时间:2014-04-13 20:55:24      阅读:470      评论:0      收藏:0      [点我收藏+]

原题:《数据结构与算法分析C++描述(第三版)》练习2.27

问题描述:N*N矩阵,每一行从左到右增加,每一列从上到下增加。给出O(N)最坏情形算法决定是否数X在该矩阵中。

代码:

bubuko.com,布布扣
 1 #include<iostream>
 2 #include<vector>
 3 #include<fstream>
 4 #include<sstream>
 5 
 6 using namespace std;
 7 
 8 int searchx(vector<vector<int> > v,int x)
 9 {
10     int i(0),j(0);
11     i=v.size()-1;
12     while(j<v.size()&&i>=0)
13     {
14         while(v[i][j]<x) j++;
15         if(v[i][j]==x)   return 0;
16         i--;
17     }
18     return -1;
19 }
20 
21 int main()
22 {
23     fstream myfile("2.27.txt");
24     if(!myfile)
25     {
26         cerr<<"error"<<endl;
27         return -1;
28     }
29     string line;
30     int word;
31     vector<int> tv;
32     vector<vector<int> > v;
33     while(getline(myfile,line))
34     {
35         tv.clear();
36         istringstream stream(line);
37         while(stream>>word) tv.push_back(word);
38         v.push_back(tv);
39     }
40     myfile.close();
41     int x;
42     cin>>x;
43     int result = searchx(v,x);
44     if(result==0) cout<<"find the number in matrix"<<endl;
45     else cout<<"can not find the number in matrix"<<endl;
46     return 0;
47 }
bubuko.com,布布扣

 注:文件2.27.txt中存储矩阵。

判断数X是否在矩阵中,布布扣,bubuko.com

判断数X是否在矩阵中

原文:http://www.cnblogs.com/moren/p/3662191.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!