注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
Handshake一上来简单聊了下,就开始做题。做的题目是黑白棋盘,然后,要是白的能连在一起,从左下到右!
下面是代码:- import java.util.*;
- class Main {
- public static boolean shortestPath(String[][] grid){
- int row=grid.length;
- int column=grid[0].length;
- if(grid[row-1][0]=="black"||grid[0][column-1]=="black"){
- return false;
- }
- int[] dx={-1,0,1};
- int[] dy={-1,0,1};
- Queue<int[]> queue = new LinkedList<>();
- queue.offer(new int[]{row-1,0});
- grid[row-1][0]="black";
- while(!queue.isEmpty()){
- int[] temp=queue.poll();
- int x=temp[0];
- int y=temp[1];
- if(x==0&&y==column-1){
- return true;
- }
- for(int i=0;i<dx.length;i++){
- for(int j=0;j<dy.length;j++){
- int nx=x+dx[i];
- int ny=y+dy[j];
- if(nx>=0&&nx<row&&ny>=0&&ny<column&&grid[nx][ny]=="white"){
- queue.offer(new int[]{nx,ny});
- grid[nx][ny]="black";
- }
- }
- }
- }
- return false;
- }
- public static void main(String[] args){
- String[][] grid={{"black","black","white"},{"black","white","white"},{"white","black","black"}};
- System.out.println(shortestPath(grid));
- }
- }
复制代码 |