Q:

Why am i getting "terminated due to Timeout" here?

I'm getting through the first 2 testcases but all the other testcases are failed because of the timeout error. Can you please tell me what i'm doing wrong? 
Link - https://www.hackerrank.com/challenges/java-1d-array
My Code :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to     STDOUT. Your class should be named Solution. */

    Scanner scan = new Scanner(System.in);
    int T,n,m;
    int[] A = new int[5000];
    int a = 0;
    int flag=1;
    T = scan.nextInt();
    if((T>=1)&&(T<=5000))
    {   
      while(T!=0)
       {
        n = scan.nextInt();
        m = scan.nextInt();
        if(((n>=2)&&(n<=100))&&((m>=0)&&(m<=100)))
        { 
         for(int i=0;i<n;i++)
         {
             A[i]=scan.nextInt();
         }
         for(int i=n;i<n+m;i++)
         {
             A[i]=0;
         }
        while((a>=0)&&(a<n)&&(flag==1))
         {
          if(A[a+1]==0)
          {
              a+=1;
          }
          else if(A[a+m]==0)
          {
              a+=m;
          }
          else if(A[a+m-1]==0) 
          {
            a-=1;  
          }
          else 
          {
              flag=0;
          }  
         }
         if(a>=n)
         {
             System.out.println("YES");
         }
         else if(flag==0||a<0)
         {
             System.out.println("NO");
             flag=1;
         }
         T--;
         a=0;
         }
        }  
    }
 }
}

A:

First, your test if(A[a+m-1]==0) is wrong. It should be if(A[a-1]==0).

Your code will enter an infinite loop.
Let's say m is 2, and input is 0 0 1 1.
Iteration 1: Move forward 1.
Iteration 2: Cannot move forward 1 or 2, so move backwards 1.
Iteration 3: Move forward 1.
Iteration 4: Cannot move forward 1 or 2, so move backwards 1.
Iteration 5: Move forward 1.
Iteration 6: Cannot move forward 1 or 2, so move backwards 1.
 . . .

Also, what if m is 4 and input is 0 0 0 1 0 1 0 1 0 1 1 1.
Forward 1, 1, 4, stuck.
However 4, 4, 4, win. You don't backtrack to try this combo.
If you then try moving forward m before trying to move forward 1, it won't help.
Still m is 4 and input is 0 0 0 1 0 1 0 1 1 1.
Forward 4, stuck.
However 1, 1, 4, 4, win. You don't backtrack to try this combo.
Your logic needs backtracking, e.g. using recursion.

