-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay26.cpp
More file actions
85 lines (61 loc) · 1.84 KB
/
Day26.cpp
File metadata and controls
85 lines (61 loc) · 1.84 KB
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
77
78
79
80
81
82
83
84
85
/*
This problem was asked by Slack.
You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the bottom right corner?
You can only move right and down. 0 represents an empty space while 1 represents a wall you cannot walk through.
For example, given the following matrix:
[[0, 0, 1],
[0, 0, 1],
[1, 0, 0]]
Return two, as there are only two ways to get to the bottom right:
Right, down, down, right
Down, right, down, right
The top left corner and bottom right corner will always be 0.
*/
#include <bits/stdc++.h>
using namespace std;
void bfs(int &res, vector<vector<int>> &matrix, vector<vector<bool>> &visited, int i, int j, int rows, int cols, int dirs[2][2])
{
if (i == rows - 1 and j == cols - 1)
{
res++;
return;
}
visited[i][j] = true;
for (int k = 0; k < 2; k++)
{
int newI = i + dirs[k][0];
int newJ = j + dirs[k][1];
if (newI < 0 or newI >= rows or newJ < 0 or newJ >= cols)
continue;
if (matrix[newI][newJ] == 1 or visited[newI][newJ])
continue;
bfs(res, matrix, visited, newI, newJ, rows, cols, dirs);
}
visited[i][j] = false;
}
int countPaths(vector<vector<int>> &matrix)
{
if (matrix.empty() || matrix[0].empty())
return 0;
int rows = matrix.size();
int cols = matrix[0].size();
if (matrix[0][0] == 1 || matrix[rows - 1][cols - 1] == 1)
return 0;
int res = 0;
int dirs[2][2] = {
{1, 0},
{0, 1},
};
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
bfs(res, matrix, visited, 0, 0, rows, cols, dirs);
return res;
}
int main()
{
vector<vector<int>> matrix = {
{0, 0, 1},
{0, 0, 1},
{1, 0, 0}};
cout << "Total Paths : " << countPaths(matrix) << endl;
return 0;
}