将相连的圈变形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012017783/article/details/80686502

原题不一样,我理解有偏差!

import java.util.ArrayList;
public class Solution {
     class Point{
         int x;
         int y;
        public Point(int i,int j){
           x=i;
           y=j;
        }
    }
    public void solve(char[][] board) {
        if(board==null||board.length==0||board[0].length==0){
          return ;
        }

       ArrayList<Point>list=new ArrayList<>();
        for(int i=0;i!=board.length;i++){

             for(int j=0;j!=board[0].length;j++){

                    if(board[i][j]=='O'){
                         //判断上下左右是否是'O'
                        //上
                        if(i-1>=0)
                        {
                          if(board[i-1][j]=='O')
                          {
                              Point point=new Point(i,j);
                              list.add(point);
                              continue;
                          }

                        }
                        //下
                        if(i+1<board.length)
                        {
                          if(board[i+1][j]=='O'){
                              Point point=new Point(i,j);
                              list.add(point);
                              continue;
                          }

                        }
                        //左
                        if(j-1>=0){
                          if(board[i][j-1]=='O'){
                              Point point=new Point(i,j);
                              list.add(point);
                              continue;
                          }
                        }
                        //右
                        if(j+1<board[0].length){
                           if(board[i][j+1]=='O'){
                              Point point=new Point(i,j);
                              list.add(point);
                              continue;
                           }
                        }
                    }
             }
        }
        for(Point point:list){
             board[point.x][point.y]='X';
        }

}

    //打印二维字符串数组
    public void printArr(char[][]board){
        for(int i=0;i!=board.length;i++){
             for(int j=0;j!=board[0].length;j++){
                System.out.print(board[i][j]+" ");
             }
             System.out.println();
        }
        System.out.println();
    }
    public static void main(String[]args){
        System.out.println("Hello World!");
        /*char[][]board={
            {'X','X','X','X'},
            {'X','O','O','X'},
            {'X','X','O','X'},
            {'X','O','X','X'}
        };*/
        char[][]board={
           {'O','O'},
           {'O','O'}
        };
        Solution s=new Solution();
        s.printArr(board);
        s.solve(board);
        s.printArr(board);
    }
}

这里写图片描述

阅读更多
换一批

没有更多推荐了,返回首页