宽度优先遍历 BFS

2019-01-17  本文已影响0人  YOLO哈哈哈

宽度优先遍历 BFS

1· 机器人的运动范围 (13 剑指offer )
public int movingCount(int threshold , int rows , int cols ){  
   if(rows <=0 || cols <= 0)
     return 0;
    int res = 0; 
   boolean [][] visited = new boolean [rows][cols];
   Queue<int[]> queue = new LinkedList<>();
   int[] dx = {-1, 0, 1, 0},  dy = {0, 1, 0, -1}; 
   queue.offer(new int[] {0,0});
   while( !queue.isEmpty()){
       int[] arr = queue.poll();
       if( get_sum_Digit(arr[0]) + get_sum_Digit(arr[1]) > threshold || arr[0] >= rows
           || arr[1] >= cols || arr[0] < 0 || arr[1] < 0 || visited[arr[0]][arr[1]] ) continue;
       res ++; 
       visited[arr[0]][arr[1]] = true; 
       for(int i=0; i<4; i++) {
           queue.offer(new int[]{ arr[0] + dx[i] , arr[1] +  dy[i]}); 
       }           
   }  /* while */
   return  res;
}

public int get_sum_Digit(int input) {
   int sum = 0;
   while(input != 0) {
     sum += input %10;
     input /= 10;
   }
 return  sum;
}
上一篇下一篇

猜你喜欢

热点阅读