# Very Concise C++ solution using DFS and bit mask

• ``````class Solution {
public:
vector<pair<int, int>> res;
vector<vector<int>> visited;
void dfs(vector<vector<int>>& matrix, int x, int y, int pre, int preval){
if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()
|| matrix[x][y] < pre || (visited[x][y] & preval) == preval)
return;
visited[x][y] |= preval;
if (visited[x][y] == 3) res.push_back({x, y});
dfs(matrix, x + 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x - 1, y, matrix[x][y], visited[x][y]);
dfs(matrix, x, y + 1, matrix[x][y], visited[x][y]); dfs(matrix, x, y - 1, matrix[x][y], visited[x][y]);
}

vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
if (matrix.empty()) return res;
int m = matrix.size(), n = matrix[0].size();
visited.resize(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
dfs(matrix, i, 0, INT_MIN, 1);
dfs(matrix, i, n - 1, INT_MIN, 2);
}
for (int i = 0; i < n; i++) {
dfs(matrix, 0, i, INT_MIN, 1);
dfs(matrix, m - 1, i, INT_MIN, 2);
}
return res;
}
};
``````

• so cool !!!
so concise !!!

• Great solution! But I think `matrix[x][y] < 0` is useless, you could remove it.
BTW, Java Solution based on your post is:

``````public class Solution {
private List<int[]> res = new ArrayList<>();
private int[][] visited;
private int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};

public List<int[]> pacificAtlantic(int[][] matrix) {
if (matrix == null || matrix.length == 0) return res;

visited = new int[matrix.length][matrix[0].length];

for (int i = 0; i < matrix.length; i++) {
dfs(matrix, i, 0, Integer.MIN_VALUE, 1);
dfs(matrix, i, matrix[0].length - 1, Integer.MIN_VALUE, 2);
}

for (int j = 0; j < matrix[0].length; j++) {
dfs(matrix, 0, j, Integer.MIN_VALUE, 1);
dfs(matrix, matrix.length - 1, j, Integer.MIN_VALUE, 2);
}

return res;
}

private void dfs(int[][] matrix, int row, int col, int preHeight, int mark) {
if (row < 0 || row >= matrix.length || col < 0 || col >= matrix[0].length
|| matrix[row][col] < preHeight || (visited[row][col] & mark) == mark) return;

visited[row][col] |= mark;
if (visited[row][col] == 3) res.add(new int[]{row, col});

for(int[] dir: dirs) {
int newRow = row + dir[0], newCol = col + dir[1];
dfs(matrix, newRow, newCol, matrix[row][col], visited[row][col]);
}
}
}
``````

• What a brilliant solution!
Here's the Python version based on your idea.

I've tried to put some comments inside, please correct me if I'm wrong.

``````class Solution(object):
def __init__(self):
self.res = []       # Stores the valid positions.
self.visited = []   # Stores the status, (1 = reachable to Pac, 2 = Atl, 3 = both)

def pacificAtlantic(self, matrix):
if not matrix or not matrix[0]: return self.res
height, width = len(matrix), len(matrix[0])
self.visited = [[0 for _ in xrange(width)] for _ in xrange(height)]
for i in xrange(height):
self.dfs(matrix, i, 0, float('-inf'), 1)
self.dfs(matrix, i, width - 1, float('-inf'), 2)
for j in xrange(width):
self.dfs(matrix, 0, j, float('-inf'), 1)
self.dfs(matrix, height - 1, j, float('-inf'), 2)
return self.res;

def dfs(self, mat, x, y, preh, prev):
# preh: height of previous position
# prev: visit status of previous position
# dfs stop when: out of boundary / current position is higher / two position has the same status
if x < 0 or x >= len(mat) or y < 0 or y >= len(mat[0]) or mat[x][y] < preh or (self.visited[x][y]&prev) == prev:
return
self.visited[x][y] |= prev     # we can see here case c will be simply useless.
if (self.visited[x][y] == 3): self.res += [x, y],
self.dfs(mat, x + 1, y, mat[x][y], self.visited[x][y])  # seek all four direction
self.dfs(mat, x - 1, y, mat[x][y], self.visited[x][y])
self.dfs(mat, x, y + 1, mat[x][y], self.visited[x][y])
self.dfs(mat, x, y - 1, mat[x][y], self.visited[x][y])``````

• @xietao0221 Yes, You are totally true.
I modified the code according to your suggestions.
Thanks

• @YJL1228 Thanks a lot

• Amazingggggggg solution buddy!!!

You use the bit to traverse the matrix and if certain point can flow in both direction, the status of that point will be 01 | 10 = 11, which is 3!!! What a great solution!

• @jasonshieh Thanks a lot.

• your code is cool. I tried this question with the regular DFS(do DFS with every point in the matrix) but I cannot get accepted. So I guess we should use the DFS from the ocean to save time?
And I tried to put

``````(visited[row][col] & mask) == mask
``````

at the first of if, like:

``````if((visited[row][col] & mask) == mask || row < 0 || row >= matrix.size() || col < 0 || col >= matrix[0].size() || matrix[row][col] < pre)
``````

I got a runtime error, do you know the reason...

• @Jiming_Ye
Hi, the reason of getting Run Time Error should not be Time Limit Exceeded. If now we have row < 0 || row >= matrix.size() || col < 0 || col >= matrix[0].size(), and you now first check (visited[row][col] & mask) == mask, there is an error that the array subscript is out-of-bounds, there will be Run Time Error, so you must check the subscript first and then put them into the vector.

• @jasonshieh thanks, I didn't think about that...

• Nice solution!!
I can not understand the condition in your code as "(visited[x][y] & preval) == preval)". So I slightly made some modification as "visited[i][j]==3||visited[i][j]==label" to ease my understanding!

class Solution {

public:
vector<pair<int, int>> res;
vector<vector<int>> visited;

``````void dfs(int i,int j,vector<vector<int>>& matrix,int pre,int label){
if(i<0||i>matrix.size()-1||j<0||j>matrix[0].size()-1||matrix[i][j]<pre||visited[i][j]==3||visited[i][j]==label)
return;
visited[i][j]+=label;
if(visited[i][j]==3) res.push_back({i,j});
dfs(i+1,j,matrix,matrix[i][j],label);
dfs(i-1,j,matrix,matrix[i][j],label);
dfs(i,j+1,matrix,matrix[i][j],label);
dfs(i,j-1,matrix,matrix[i][j],label);
}

vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
if(matrix.empty()) return res;
int m=matrix.size();
int n=matrix[0].size();
visited.resize(m,vector<int>(n,0));
for(int j=0;j<n;j++){
dfs(0,j,matrix,INT_MIN,1);
dfs(m-1,j,matrix,INT_MIN,2);
}

for(int i=0;i<m;i++){
dfs(i,0,matrix,INT_MIN,1);
dfs(i,n-1,matrix,INT_MIN,2);
}
return res;
}
``````

};

• Genius.
Here is a c++ version of the same Method using two stack instead of recursion.
Though the performances of the two version are nearly identical.

``````class Solution
{

public:

vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix)
{
vector<pair<int, int> > ret;
stack <pair<int, int> > s1;
stack <pair<int, int> > s2;
vector <vector<int> > intermidiate;
int hSize, vSize;
vSize = matrix.size();
if (vSize)
{
hSize = matrix[0].size();
if (hSize)
{
intermidiate.resize(vSize, vector<int>(hSize, 0));
for (int index = 0; index < vSize; index++)
{
s1.push(pair<int, int>(index, 0));
s2.push(pair<int, int>(1, INT_MIN));
s1.push(pair<int, int>(index, hSize - 1));
s2.push(pair<int, int>(2, INT_MIN));
}
for (int index = 0; index < hSize; index++)
{
s1.push(pair<int, int>(0, index));
s2.push(pair<int, int>(1, INT_MIN));
s1.push(pair<int, int>(vSize - 1, index));
s2.push(pair<int, int>(2, INT_MIN));
}
while (!s1.empty())
{
pair<int, int> pos = s1.top(), meta = s2.top();
int vPos = pos.first, hPos = pos.second, previousValue = meta.second, flag = meta.first;
s1.pop();
s2.pop();
if (vPos >= 0 && vPos < vSize && hPos >= 0 && hPos < hSize && matrix[vPos][hPos] >= previousValue &&
(intermidiate[vPos][hPos]&flag) == 0)
{
intermidiate[vPos][hPos] = intermidiate[vPos][hPos] | flag;
if (intermidiate[vPos][hPos] == 3)
{
cout << vPos << ' ' << hPos << endl;
ret.push_back(pos);
}
s1.push(pair<int, int>(vPos - 1, hPos));
s2.push(pair<int, int>(flag, matrix[vPos][hPos]));
s1.push(pair<int, int>(vPos + 1, hPos));
s2.push(pair<int, int>(flag, matrix[vPos][hPos]));
s1.push(pair<int, int>(vPos, hPos - 1));
s2.push(pair<int, int>(flag, matrix[vPos][hPos]));
s1.push(pair<int, int>(vPos, hPos + 1));
s2.push(pair<int, int>(flag, matrix[vPos][hPos]));
}
}
}
}
return ret;
}
``````

};

• @xinqrs thanks i too couldn't understand that part of it.

• @YJL1228 Thanks. Ur comments help a lot.

• I'm wondering what does `visited[x][y] & preval` mean?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.