判断数X是否在矩阵中

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

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

代码:

 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 }

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

posted @ 2014-04-13 14:06  Will Lau  阅读(360)  评论(0编辑  收藏  举报