-
Notifications
You must be signed in to change notification settings - Fork 0
/
1479-can-reach-the-endpoint.cpp
76 lines (64 loc) · 1.97 KB
/
1479-can-reach-the-endpoint.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
[地址](https://www.lintcode.com/problem/can-reach-the-endpoint/description)
// 大小为 m*n 的map
// 1 代表空地,0 代表障碍物,9代表终点。
// 只能↓或者→走
// 请问如果你从 (0, 0) 开始能否到达终点?
// 思路:BFS。
// 易错点:边界控制。
class Solution {
public:
/**
* @param matrix: the matrix
* @return: can you reach the endpoint
*/
bool reachEndpoint(vector<vector<int>> &matrix) {
int m = matrix.size(), n=matrix[0].size();
queue<pair<int, int>> Q;
int i=0, j=0;
Q.push(make_pair(0,0));
pair<int, int> cur;
while(!Q.empty())
{
cur = Q.front();
Q.pop();
i = cur.first;
j = cur.second;
if(matrix[i][j]==9) return true;
if(i+1<m && (matrix[i+1][j]==1 || matrix[i+1][j]==9))
Q.push(make_pair(i+1,j));
if(j+1<n && (matrix[i][j+1]==1 || matrix[i][j+1]==9) )
Q.push(make_pair(i,j+1));
}
return false;
// Write your code here
}
};
// 两种方法本质无区别
class Solution {
public:
/**
* @param matrix: the matrix
* @return: can you reach the endpoint
*/
bool reachEndpoint(vector<vector<int>> &matrix) {
int m = matrix.size();
int n = matrix[0].size();
queue<pair<int,int>>Q;
Q.push(make_pair(0,0));
pair<int,int>cur;
while(!Q.empty())
{
cur = Q.front();
Q.pop();
int i = cur.first;
int j = cur.second;
if((i+1<m && matrix[i+1][j]==9) || (j+1<n && matrix[i][j+1]==9))
return true;
if(i+1<m && matrix[i+1][j]==1)
Q.push(make_pair(i+1, j));
if(j+1<n && matrix[i][j+1]==1)
Q.push(make_pair(i, j+1));
}
return false;
}
};