MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

RegionsCutBySlashes.java:1–49  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2 int rows;
3 int cols;
4 int dir[][] = {{-1,0},{0,1},{1,0},{0,-1}};
5 //visit all nodes of a component using DFS
6 public void dfs(int row, int col, int matrix[][]){
7 //out of bound, already visited, obstacle
8 if(row<0 || row>=rows || col<0 || col>=cols || matrix[row][col]==1){
9 return;
10 }
11 matrix[row][col] = 1;
12 for(int i=0;i<4;i++){
13 dfs(row + dir[i][0], col + dir[i][1], matrix);
14 }
15 }
16 public int regionsBySlashes(String[] grid) {
17 //create a 3*3 grid
18 int size = grid.length;
19 rows = size*3;
20 cols = size*3;
21 int matrix[][] = new int[size*3][size*3];
22 for(int i=0;i<size;i++){
23 for(int j=0;j<size;j++){
24 int row = i*3;
25 int col = j*3;
26 if(grid[i].charAt(j) == '/'){
27 matrix[row][col+2] = 1;
28 matrix[row+1][col+1] = 1;
29 matrix[row+2][col] = 1;
30 }else if(grid[i].charAt(j) == '\\'){
31 matrix[row][col] = 1;
32 matrix[row+1][col+1] = 1;
33 matrix[row+2][col+2] = 1;
34 }
35 }
36 }
37 int count=0;
38 for(int i=0;i<size*3;i++){
39 for(int j=0;j<size*3;j++){
40 if(matrix[i][j]==0){
41 dfs(i,j,matrix);
42 count++;
43 }
44 }
45 }
46 return count;
47
48 }
49}
50

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected