题解 | #二维数组中的查找#
二维数组中的查找
http://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
BFS法
提交结果:答案正确 运行时间:8ms 占用内存:1528KB 使用语言:C++ 用例通过率:100.00%
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int m = array.size();
if(m == 0) return false;
int n = array[0].size();
if(n == 0) return false;
vector<vector<bool>> visited(m,(vector<bool>(n,false)));
deque<pair<int,int>> path;
path.push_back({0,0});
while(!path.empty())
{
auto temp = path.front();
int i = temp.first;
int j = temp.second;
path.pop_front();
if(array[i][j] == target)
return true;
if(visited[i][j] == false && array[i][j] < target)
{
visited[i][j] = true;
if(i+1 == m && j+1 != n)
{
path.push_back({i,j+1});
}
else if(i+1 != m && j+1 == n)
{
path.push_back({i+1,j});
}
else if(i+1 == m && j+1 == n)
{
}
else
{
path.push_back({i+1,j});
path.push_back({i,j+1});
}
}
if(array[i][j] > target)
{
visited[i][j] = true;
}
}
return false;
}
};
查看13道真题和解析