|
| 1 | +public class Solution { |
| 2 | + |
| 3 | + int solve(String[] board , int n, int m) |
| 4 | + { |
| 5 | + // Write your code here. |
| 6 | + char [][] graph = new char[n][m]; |
| 7 | + boolean [][] visited = new boolean[n][m]; |
| 8 | + |
| 9 | + |
| 10 | + for(int i=0;i<n;i++) |
| 11 | + { |
| 12 | + for(int j=0;j<m;j++) |
| 13 | + { |
| 14 | + graph[i][j] =board[i].charAt(j); |
| 15 | + //System.out.print(graph[i][j]); |
| 16 | + } |
| 17 | + //System.out.println(); |
| 18 | + } |
| 19 | + |
| 20 | + for(int i=0;i<n;i++) |
| 21 | + { |
| 22 | + for(int j=0;j<m;j++) |
| 23 | + { |
| 24 | + char c = graph[i][j]; |
| 25 | + |
| 26 | + if(c=='C') |
| 27 | + { |
| 28 | + visited[i][j] = true; |
| 29 | + boolean ans = findPath(graph,visited,i,j,1); |
| 30 | + |
| 31 | + if(ans == true) |
| 32 | + return 1; |
| 33 | + |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + return 0; |
| 38 | + |
| 39 | + } |
| 40 | + public static boolean findPath(char[][]graph, boolean [][]visited,int row, int col, int start) |
| 41 | + { |
| 42 | + String str = "CODINGNINJA"; |
| 43 | + if(start==str.length()) |
| 44 | + return true; |
| 45 | + int n =graph.length; |
| 46 | + int m = graph[0].length; |
| 47 | + //LinkedList <String> side =new LinkedList <String>(); |
| 48 | + int [] side = new int[16]; |
| 49 | + side = getNeighbour(row,col); |
| 50 | + |
| 51 | + for(int i=0;i<16;i=i+2) |
| 52 | + { |
| 53 | + int cur_row = side[i]; |
| 54 | + int cur_col = side[i+1]; |
| 55 | + if(cur_row<0 || cur_col <0 || cur_row>=n || cur_col>=m) |
| 56 | + { |
| 57 | + continue; |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + if(visited[cur_row][cur_col]==false && graph[cur_row][cur_col]==str.charAt(start)) |
| 62 | + { |
| 63 | + visited[cur_row][cur_col] =true; |
| 64 | + boolean ans = findPath(graph,visited,cur_row,cur_col,start+1); |
| 65 | + if(ans == true) |
| 66 | + return true; |
| 67 | + else |
| 68 | + visited[cur_row][cur_col] = false; |
| 69 | + |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + return false; |
| 74 | + |
| 75 | + |
| 76 | + } |
| 77 | + public static int [] getNeighbour(int row,int col) |
| 78 | + { |
| 79 | + int ans [] = new int[16]; |
| 80 | + //right |
| 81 | + ans[0]= row; |
| 82 | + ans[1]= col+1; |
| 83 | + //down |
| 84 | + ans[2]= row+1; |
| 85 | + ans[3]= col; |
| 86 | + //left |
| 87 | + ans[4]= row; |
| 88 | + ans[5]= col-1; |
| 89 | + //up |
| 90 | + ans[6]= row-1; |
| 91 | + ans[7]= col; |
| 92 | + //diagona; |
| 93 | + ans[8]= row+1; |
| 94 | + ans[9]= col+1; |
| 95 | + //diagonal |
| 96 | + ans[10]= row-1; |
| 97 | + ans[11]= col-1; |
| 98 | + |
| 99 | + //right diagonal |
| 100 | + ans[12]= row-1; |
| 101 | + ans[13]= col+1; |
| 102 | + |
| 103 | + //right dia |
| 104 | + ans[14]= row+1; |
| 105 | + ans[15]= col-1; |
| 106 | + |
| 107 | + return ans; |
| 108 | + } |
| 109 | + |
| 110 | +} |
0 commit comments