8.10 Paint Fill

If given PaintFill(screen, 2, 2, Color.White), we should have:
这里写图片描述

Basically we do DFS, the code is shown as following:

    public enum Colors{ WHITE, BLACK, GREEN, RED, YELLOW};

    public static boolean PaintFillHelper(Colors[][] screen, int row, int col, Colors oldColor, Colors newColor){
        if(row < 0 || row >= screen.length || col < 0 || col >= screen.length) return false;//the point we choose is out of bound
        if(screen[row][col] == oldColor){
            screen[row][col] = newColor;
            PaintFillHelper(screen, row+1, col, oldColor, newColor);
            PaintFillHelper(screen, row-1, col, oldColor, newColor);
            PaintFillHelper(screen, row, col+1, oldColor, newColor);
            PaintFillHelper(screen, row, col-1, oldColor, newColor);
        }
        return true;
    }

    public static boolean PaintFill(Colors[][] screen, int row, int col, Colors newColor){
        if(screen[row][col] == newColor) return false;//the point we choose already have the new color;
        else  return PaintFillHelper(screen, row, col, screen[row][col], newColor);
    }

    // Following code is for testing
    public static String PrintColor(Colors c) {
        switch(c) {
        case BLACK:
            return "B";
        case WHITE:
            return "W";
        case RED:
            return "R";
        case YELLOW:
            return "Y";
        case GREEN:
            return "G";
        }
        return "X";
    }

    public static void PrintScreen(Colors[][] screen) {
        for (int r = 0; r < screen.length; r++) {
            for (int c = 0; c < screen[0].length; c++) {
                System.out.print(PrintColor(screen[r][c]));
            }
            System.out.println();
        }
    }

    public static int randomInt(int n) {
        return (int) (Math.random() * n);
    }

    public static void main(String[] args) {
        int N = 10;
        Colors[][] screen = new Colors[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                screen[i][j] = Colors.BLACK;
            }           
        }
        for (int i = 0; i < 100; i++) {
            screen[randomInt(N)][randomInt(N)] = Colors.GREEN;
        }
        PrintScreen(screen);
        PaintFill(screen, 0, 0, Colors.WHITE);
        System.out.println();
        PrintScreen(screen);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值