import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author unknown
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        DSolveTheMaze solver = new DSolveTheMaze();
        solver.solve(1, in, out);
        out.close();
    }

    static class DSolveTheMaze {
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        char[][] mat;
        int n;
        int m;
        boolean[][] vis;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int ntc = in.nextInt();
            while ((ntc--) > 0) {
                n = in.nextInt();
                m = in.nextInt();
                int gc = 0;
                int bc = 0;
                mat = new char[n][m];
                vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        char ch = in.nextCharacter();
                        if (ch == 'G') {
                            gc++;
                        }
                        if (ch == 'B') {
                            bc++;
                        }
                        mat[i][j] = ch;
                    }
                }
                if (gc == 0) {
                    out.println("Yes");
                    continue;
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        if (mat[i][j] == 'B') {
                            for (int k = 0; k < 4; k++) {
                                int newx = dx[k] + i;
                                int newy = dy[k] + j;
                                if (isvalid(newx, newy) && mat[newx][newy] == '.') {
                                    mat[newx][newy] = '#';
                                }
                            }
                        }
                    }
                }
                if (mat[n - 1][m - 1] == '.') {
                    mat[n - 1][m - 1] = '#';
                }
                bfs(n - 1, m - 1);
                boolean ok = true;
//            vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (mat[i][j] == 'G' && !vis[i][j]) {
                            ok = false;
                            break;
                        } else if (mat[i][j] == 'B' && vis[i][j]) {
                            ok = false;
                            break;
                        }
                    }
                }
                if (ok) {
                    out.println("Yes");
                } else {
                    out.println("No");
                }
//            for(int i = )
            }
        }

        void bfs(int x, int y) {
            ArrayDeque<Integer> queue = new ArrayDeque<>();
            queue.addLast(x);
            queue.addLast(y);
            vis[x][y] = true;
            while (!queue.isEmpty()) {
                int u = queue.removeFirst();
                int v = queue.removeFirst();
                for (int i = 0; i < 4; i++) {
                    int newx = u + dx[i];
                    int newy = v + dy[i];
                    if (isvalid(newx, newy) && mat[newx][newy] != '#' && !vis[newx][newy]) {
//                    if(newx == n-1 && newy == m-1){
//                        return true;
//                    }
                        vis[newx][newy] = true;
                        queue.addLast(newx);
                        queue.addLast(newy);
                    }
                }
            }
//        return false;
        }

        boolean isvalid(int x, int y) {
            if (x < 0 || x >= n) {
                return false;
            }
            if (y < 0 || y >= m) {
                return false;
            }
            return true;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; ++i) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author unknown
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        DSolveTheMaze solver = new DSolveTheMaze();
        solver.solve(1, in, out);
        out.close();
    }

    static class DSolveTheMaze {
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        char[][] mat;
        int n;
        int m;
        boolean[][] vis;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int ntc = in.nextInt();
            while ((ntc--) > 0) {
                n = in.nextInt();
                m = in.nextInt();
                int gc = 0;
                int bc = 0;
                mat = new char[n][m];
                vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        char ch = in.nextCharacter();
                        if (ch == 'G') {
                            gc++;
                        }
                        if (ch == 'B') {
                            bc++;
                        }
                        mat[i][j] = ch;
                    }
                }
                if (gc == 0) {
                    out.println("Yes");
                    continue;
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        if (mat[i][j] == 'B') {
                            for (int k = 0; k < 4; k++) {
                                int newx = dx[k] + i;
                                int newy = dy[k] + j;
                                if (isvalid(newx, newy) && mat[newx][newy] == '.') {
                                    mat[newx][newy] = '#';
                                }
                            }
                        }
                    }
                }
                boolean ok = true;
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        vis = new boolean[n][m];
                        if (mat[i][j] == 'G' && !bfs(i, j)) {
                            ok = false;
                            break;
                        } else if (mat[i][j] == 'B' && bfs(i, j)) {
                            ok = false;
                            break;
                        }
                    }
                }
                if (ok) {
                    out.println("Yes");
                } else {
                    out.println("No");
                }
//            for(int i = )
            }
        }

        boolean bfs(int x, int y) {
            ArrayDeque<Integer> queue = new ArrayDeque<>();
            queue.addLast(x);
            queue.addLast(y);
            vis[x][y] = true;
            while (!queue.isEmpty()) {
                int u = queue.removeFirst();
                int v = queue.removeFirst();
                vis[u][v] = true;
                for (int i = 0; i < 4; i++) {
                    int newx = u + dx[i];
                    int newy = v + dy[i];
                    if (isvalid(newx, newy) && mat[newx][newy] != '#' && !vis[newx][newy]) {
                        if (newx == n - 1 && newy == m - 1) {
                            return true;
                        }
                        queue.addLast(newx);
                        queue.addLast(newy);
                    }
                }
            }
            return false;
        }

        boolean isvalid(int x, int y) {
            if (x < 0 || x >= n) {
                return false;
            }
            if (y < 0 || y >= m) {
                return false;
            }
            return true;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; ++i) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author unknown
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        DSolveTheMaze solver = new DSolveTheMaze();
        solver.solve(1, in, out);
        out.close();
    }

    static class DSolveTheMaze {
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        char[][] mat;
        int n;
        int m;
        boolean[][] vis;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int ntc = in.nextInt();
            while ((ntc--) > 0) {
                n = in.nextInt();
                m = in.nextInt();
                int gc = 0;
                int bc = 0;
                mat = new char[n][m];
                vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        char ch = in.nextCharacter();
                        if (ch == 'G') {
                            gc++;
                        }
                        if (ch == 'B') {
                            bc++;
                        }
                        mat[i][j] = ch;
                    }
                }
                if (gc == 0) {
                    out.println("Yes");
                    continue;
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        if (mat[i][j] == 'B') {
                            for (int k = 0; k < 4; k++) {
                                int newx = dx[k] + i;
                                int newy = dy[k] + j;
                                if (isvalid(newx, newy) && mat[newx][newy] == '.') {
                                    mat[newx][newy] = '#';
                                }
                            }
                        }
                    }
                }
                boolean ok = true;
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        vis = new boolean[n][m];
                        if (mat[i][j] == 'G' && !bfs(i, j)) {
                            ok = false;
                            break;
                        } else if (mat[i][j] == 'B' && bfs(i, j)) {
                            ok = false;
                            break;
                        }
                    }
                }
                if (ok) {
                    out.println("Yes");
                } else {
                    out.println("No");
                }
//            for(int i = )
            }
        }

        boolean bfs(int x, int y) {
            ArrayDeque<Integer> queue = new ArrayDeque<>();
            queue.addLast(x);
            queue.addLast(y);
            vis[x][y] = true;
            while (!queue.isEmpty()) {
                int u = queue.removeFirst();
                int v = queue.removeFirst();
                vis[u][v] = true;
                for (int i = 0; i < 4; i++) {
                    int newx = u + dx[i];
                    int newy = v + dy[i];
                    if (isvalid(newx, newy) && mat[newx][newy] != '#' && !vis[newx][newy]) {
                        if (newx == n - 1 && newy == m - 1) {
                            return true;
                        }
                        queue.addLast(newx);
                        queue.addLast(newy);
                    }
                }
            }
            return false;
        }

        boolean isvalid(int x, int y) {
            if (x < 0 || x >= n) {
                return false;
            }
            if (y < 0 || y >= m) {
                return false;
            }
            return true;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; ++i) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author unknown
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        DSolveTheMaze solver = new DSolveTheMaze();
        solver.solve(1, in, out);
        out.close();
    }

    static class DSolveTheMaze {
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        char[][] mat;
        int n;
        int m;
        boolean[][] vis;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int ntc = in.nextInt();
            while ((ntc--) > 0) {
                n = in.nextInt();
                m = in.nextInt();
                int gc = 0;
                int bc = 0;
                mat = new char[n][m];
                vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        char ch = in.nextCharacter();
                        if (ch == 'G') {
                            gc++;
                        }
                        if (ch == 'B') {
                            bc++;
                        }
                        mat[i][j] = ch;
                    }
                }
                if (gc == 0) {
                    out.println("Yes");
                    continue;
                }
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        if (mat[i][j] == 'B') {
                            for (int k = 0; k < 4; k++) {
                                int newx = dx[k] + i;
                                int newy = dy[k] + j;
                                if (isvalid(newx, newy) && mat[newx][newy] == '.') {
                                    mat[newx][newy] = '#';
                                }
                            }
                        }
                    }
                }
                if (mat[n - 1][m - 1] == '.') {
                    mat[n - 1][m - 1] = '#';
                }
                bfs(n - 1, m - 1);
                boolean ok = true;
//            vis = new boolean[n][m];
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < m; j++) {
                        if (mat[i][j] == 'G' && !vis[i][j]) {
                            ok = false;
                            break;
                        } else if (mat[i][j] == 'B' && vis[i][j]) {
                            ok = false;
                            break;
                        }
                    }
                }
                if (ok) {
                    out.println("Yes");
                } else {
                    out.println("No");
                }
//            for(int i = )
            }
        }

        void bfs(int x, int y) {
            ArrayDeque<Integer> queue = new ArrayDeque<>();
            queue.addLast(x);
            queue.addLast(y);
            vis[x][y] = true;
            while (!queue.isEmpty()) {
                int u = queue.removeFirst();
                int v = queue.removeFirst();
                for (int i = 0; i < 4; i++) {
                    int newx = u + dx[i];
                    int newy = v + dy[i];
                    if (isvalid(newx, newy) && mat[newx][newy] != '#' && !vis[newx][newy]) {
//                    if(newx == n-1 && newy == m-1){
//                        return true;
//                    }
                        vis[newx][newy] = true;
                        queue.addLast(newx);
                        queue.addLast(newy);
                    }
                }
            }
//        return false;
        }

        boolean isvalid(int x, int y) {
            if (x < 0 || x >= n) {
                return false;
            }
            if (y < 0 || y >= m) {
                return false;
            }
            return true;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; ++i) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


from math import ceil

def min_digits_for_sum_increase(digit_count, delta):
    num_digits = 0

    for digit in xrange(10):
        current_digits = min(
            ceil(delta / (10.0 - digit)),
            digit_count[digit]
            )

        current_digits = int(current_digits)

        delta -= current_digits
        num_digits += current_digits

    return num_digits

k = int(raw_input())

digits = [0 for i in xrange(10)]

sum_digits = 0

for c in raw_input():
    d = ord(c) - ord('0')

    digits[d] += 1

    sum_digits += d

delta = k - sum_digits

if delta <= 0:
    print 0
else:
    print min_digits_for_sum_increase(digits, delta)


from math import ceil

def min_digits_for_sum_increase(digit_count, delta):
    num_digits = 0

    for digit in xrange(9):
        current_digits = min(
            ceil(delta / (9.0 - digit)),
            digit_count[digit]
            )

        current_digits = int(current_digits)

        delta -= current_digits * (9 - digit)
        num_digits += current_digits

        if delta <= 0:
            break

    return num_digits

k = int(raw_input())

digits = [0 for i in xrange(10)]

sum_digits = 0

for c in raw_input():
    d = ord(c) - ord('0')

    digits[d] += 1

    sum_digits += d

delta = k - sum_digits

if delta <= 0:
    print 0
else:
    print min_digits_for_sum_increase(digits, delta)


k = input()
n = raw_input()
ls = []
total = 0
for digit in n:
	ls.append(digit)
	total = total + int(digit)
first = ls[0]
del ls[0]
ls.sort(reverse = True)
ls.append(first)
if total >= k:
	print 0
else:
	l = len(ls)
	ans = 0
	for i in xrange(l):
		if total >= k:
			break
		else:
			diff = 9 - int(ls[i])
			total = total + diff
			ans = ans + 1
	print ans


k = input()
n = raw_input()
ls = []
total = 0
for digit in n:
	ls.append(digit)
	total = total + int(digit)
ls.sort()
if total >= k:
	print 0
else:
	l = len(ls)
	ans = 0
	for i in xrange(l):
		if total >= k:
			break
		else:
			diff = 9 - int(ls[i])
			total = total + diff
			ans = ans + 1
	print ans


k = int(raw_input())
s = map(int, list(raw_input()))
l = [0] * 10
for i in s: l[i] += 1
remaining = k - sum(s)
if remaining <= 0: print 0
else:
    ans = 0
    for i in xrange(9):
        temp = min(l[i], (remaining + 8 - i) / (9 - i))
        ans += temp
        remaining -= temp * (9 - i)
        if remaining <= 0:
            print ans
            break


k = long(raw_input())
n = map(int, list(raw_input()))
sum_n = sum(n)

if sum_n >= k: print 0
else:
	diff = k - sum_n
	summ = 0
	for i in n:
		if diff <= 0: break
		if i < 9:
			diff -= 9-i
			summ += 1
	print summ


k = long(raw_input())
n = map(int, list(raw_input()))
sum_n = sum(n)
n.sort()

if sum_n >= k: print 0
else:
	diff = k - sum_n
	summ = 0
	for i in n:
		if diff <= 0: break
		if i < 9:
			diff -= 9-i
			summ += 1
	print summ


n=input()
s=raw_input()
count=0
for i in range(len(s)):
        count+=int(s[i])
if(count>=n):
        print("0")
else:
        a=n-count
        print(a)


n=input()
s=raw_input()
count=0
for i in range(len(s)):
        count+=int(s[i])
x=n-count
if(x<=0):
        print("0")
else:
        l=map(int,list(s))
        l.sort()
        i=0
        k=0
        while(x>0):
                x-=(9-l[k])
                i+=1
                k+=1
        print(i)


n=input()
s=raw_input()
count=0
for i in range(len(s)):
        count+=int(s[i])
l=len(str(n))
x=n-count
if(x>=0):
        a=x%9
        print(a)
else:
        print(0)


k=input()
n=input()
a=[int(c) for c in str(n)]
a=sorted(a)
total=sum(a)
cnt=0
if total<k:
    t=k-total
    for i in range(len(a)):
        if cnt+9-a[i]>=t:
            print i+1
            break
        else:
            cnt+=9-a[i]
else:
    print 0


k = input()
n = raw_input()
digitos = []
for char in n:
    digitos.append(ord(char) - ord('0'))
digitos.sort()
actual = sum(digitos)
result = 0
for d in digitos:
    if actual < k:
        actual += 9 - d
        result += 1
print(result)


k = int(raw_input())

s = raw_input().strip()

freq = [0 for __ in xrange(10)]
ss = 0
for c in s:
	freq[ord(c)-ord('0')] += 1
	ss += ord(c) - ord('0')

ans = 0
for i in xrange(10):
	if ss <= k:
		x = min((ss-k+10-i+1) / (10-i), freq[i])
		ans += x
		ss += x * i

print ans


k = int(raw_input())

s = raw_input().strip()

freq = [0 for __ in xrange(10)]
ss = 0
for c in s:
	freq[ord(c)-ord('0')] += 1
	ss += ord(c) - ord('0')

ans = 0
for i in xrange(9):
	if ss < k:
		x = min((ss-k+9-i-1) / (9-i), freq[i])
		ans += x
		ss += x * (9-i)

print ans


k = int(raw_input())

s = raw_input().strip()

freq = [0 for __ in xrange(10)]
ss = 0
for c in s:
	freq[ord(c)-ord('0')] += 1
	ss += ord(c) - ord('0')

ans = 0
for i in xrange(9):
	if ss < k:
		x = min((k-ss+9-i-1) / (9-i), freq[i])
		ans += x
		ss += x * (9-i)

print ans


k = int(raw_input())

s = raw_input().strip()

freq = [0 for __ in xrange(10)]
ss = 0
for c in s:
	freq[ord(c)-ord('0')] += 1
	ss += ord(c) - ord('0')

ans = 0
for i in xrange(10):
	if ss < k:
		x = min((ss-k+10-i+1) / (10-i), freq[i])
		ans += x
		ss += x * i

print ans


k = int(raw_input())

s = raw_input().strip()

freq = [0 for __ in xrange(10)]
ss = 0
for c in s:
	freq[ord(c)-ord('0')] += 1
	ss += ord(c) - ord('0')

ans = 0
for i in xrange(9):
	if ss < k:
		x = min((ss-k+9-i+1) / (9-i), freq[i])
		ans += x
		ss += x * (9-i)

print ans


def get_closest(k, n):
    curr_sum = sum(n)
    if k <= curr_sum:
        return 0

    n.sort()
    diff = k - curr_sum
    i = 0
    while diff > 0:
        diff -= 9 - n[i]
        i += 1

    return i

k = int(raw_input())
n = list(map(int, raw_input().strip()))

print get_closest(k, n)


k = input()
n = input()
n = str(n)
l = len(str(n))
s = k
ans = [0]*l
ss = [0]*l
for i in range(l):
    ss[i] = n[i]
s2 = 0
for i in range(l):
    s2 += int(n[i])
ss.sort()
i = 1
kk = 0

if s2 >= s:
    print 0
else:
    while s - s2 > 0:
        ss2 = (9 - int(ss[l-i]))
        if ss2 != 0:
            kk += 1
        s2 += ss2
        i += 1
        #print s2
    print kk


k = input()
n = input()
n = str(n)
l = len(str(n))
s = k
ans = [0]*l
ss = [0]*l
for i in range(l):
    ss[i] = n[i]
s2 = 0
for i in range(l):
    s2 += int(n[i])
ss.sort()
i = 0
kk = 0

if s2 >= s:
    print 0
else:
    while s - s2 > 0:
        ss2 = (9 - int(ss[i]))
        if ss2 != 0:
            kk += 1
        s2 += ss2
        i += 1
        #print s2
    print kk


from collections import defaultdict
k = input()
n = list(raw_input())
n = map(int, n)
n.sort()
c = 0
for i in n: c += i
if c >= k:
    print 0
else:
    i = 0
    diff = 0
    while c < k:
        c += 9 - n[i]
        i += 1
        diff += 1
    print diff


from collections import defaultdict
k = input()
n = list(raw_input())
n = map(int, n)
n.sort()
c = 0
for i in n: c += i
if c >= k:
    print 0
else:
    i = 0
    diff = 0
    while c < k:
        c += 9 - n[i]
        diff += 1
    print diff


a=input()
b=raw_input()
l=[]
for i in b:l.append(int(i))
l.sort()
i=0
s=sum(l)
while s<a:
    s+=9-l[i]
    i+=1
print i


k = int(raw_input())
n = raw_input()
digs = [0 for _ in range(0, 10)]
sumn = 0
for s in n:
  digs[int(s)] += 1
  sumn += int(s)

ans = 0
while sumn < k:
  for d in range(0, 10):
    if digs[d] > 0:
      digs[d] -= 1
      digs[9] += 1
      sumn += 9 - d
      ans += 1
      break

print ans


k=int(raw_input())
n=raw_input()
sum=0
for i in n:
    sum+=int(i)
if(sum>=k):
    print('0')
else:
    e=k-sum
    res=0
    l=[]
    for i in n:
        l.append(int(i))
    l.sort()
    for i in l:
        if(e>0):
            e-=9-i
            res+=1
        else:
            break
    print res


def main():
	from sys import stdin,stdout
	r,w = stdin.readline,stdout.write
	k,n = int(r(),10), map(int,list(r().strip()))
	n.sort(); dig = 0; som = sum(n)
	for i in n:
		if som < k: som += 9 - i; dig += 1
	w(str(dig))
main()


def suma(num):
    digits = []
    for i in range(len(num)):
       digits.append(int(num[i]))
    return digits

def main():
    k = input()
    n = raw_input()

    result = suma(n)
    dif = k - sum(result)
    result.sort()

    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - result[count])
            count = count + 1
    print count

main()


def suma(num):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        digits.append(mod)
        num = num / 10
    return digits

def main():
    k = input()
    nn = raw_input()
    nn.strip('0')
    n = int(nn)
    result = suma(n)
    dif = k - sum(result)
    result.sort()

    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - result[count])
            count = count + 1
    print count

main()


def suma(num):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        digits.append(mod)
        num = num / 10
    return digits

def main():
    k = input()
    n = input()
    result = suma(n)
    dif = k - sum(result)
    result.sort()

    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - result[count])
            count = count + 1
    print count

main()


def suma(num):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        total = total + mod
        digits.append(mod)
        num = num / 10
    return [total, digits]

def main():
    k = input()
    n = input()
    result = suma(n)
    dif = k - result[0]
    lista = result[1]
    lista.reverse()
    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - lista.pop()
            count = count + 1
    print count

main()


def suma(num):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        total = total + mod
        digits.append(mod)
        num = num / 10
    return [total, digits]

def main():
    k = input()
    n = input()
    result = suma(n)
    dif = k - result[0]
    lista = result[1]
    lista.sort()
    lista.reverse()

    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - lista.pop())
            count = count + 1
    print count

main()


def suma(num):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        total = total + mod
        digits.append(mod)
        num = num / 10
    return [total, digits]

def main():
    k = input()
    n = input()
    result = suma(n)
    dif = k - result[0]
    lista = result[1]
    lista.reverse()
    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - lista.pop())
            count = count + 1
    print count

main()


def suma(num, k):
    total = 0
    digits = []
    while num > 0:
        mod = num % 10
        total = total + mod
        digits.append(mod)
        num = num / 10
        if(total > k):
            return [k + 1, digits]
    return [total, digits]

def main():
    k = input()
    n = input()
    result = suma(n, k)
    dif = k - result[0]
    lista = result[1]
    lista.sort()
    lista.reverse()

    count = 0
    if(dif > 0):
        while(dif > 0):
            dif = dif - (9 - lista.pop())
            count = count + 1
    print count

main()


k = input()
n = raw_input()
n = sorted(n)
ttl = sum(map(int, n))
res = 0
for dig in n:
  if ttl >= k:
    break
  ttl += 9
  ttl -= int(dig)
  res += 1
print res


k = input()
n = map(int, raw_input().split())
n.sort()
ttl = sum(n)
res = 0
for dig in n:
  if ttl >= k:
    break
  ttl += 9
  ttl -= dig
  res += 1
print res


###modular exponentiation: a^n % M
#pow(a, n, M)
### gcd: gcd(a, b)
#import fractions
#fractions.gcd(a, b)
### LCM (M, N)
#lcm = M*N/fractions.gcd(M, N)

def get_res(k, s):
    result = 0
    L = [int(z) for z in s]
    Ls = sorted(L)
    x = sum(Ls)
    if x >= k:
        return 0
    k = k-x
    i = 0
    while k > 0:
        k -= min(k, 9-Ls[i])
        i += 1
        result += 1

    return result

#N = int(raw_input())
k = int(raw_input())
s = raw_input().split(" ")[0]
result = get_res(k, s)
print "{}".format(result)


###modular exponentiation: a^n % M
#pow(a, n, M)
### gcd: gcd(a, b)
#import fractions
#fractions.gcd(a, b)
### LCM (M, N)
#lcm = M*N/fractions.gcd(M, N)

def get_res(k, s):
    result = 0
    L = [int(z) for z in s]
    Ls = sorted(L)
    #print Ls
    x = sum(Ls)
    if x >= k:
        return 0
    k = k-x
    i = 0
    while k > 0:
        k -= min(k, 9-Ls[i])
        i += 1
        result += 1

    return result

#N = int(raw_input())
k = int(raw_input())
s = raw_input().split(" ")
result = get_res(k, s)
print "{}".format(result)


k = int(raw_input())
n = int(raw_input())

q = str(n)

count = 0
s = 0
for i in q:
	s = s + int(i)

if(s >= k ):
	print 0
else:
	d = s - k
	count = count + 1
	for j in q:
		p = int(j) + d
		if(p > 9):
			a = 9 - int(j)
			d = d - a
		else:
			break
	print count


k = int(raw_input())
n = int(raw_input())

q = str(n)
q = map(int,q)
q = sorted(q)
count = 0
s = 0
for i in q:
	s = s + int(i)

if(s >= k ):
	print 0
else:
	d = (k - s)
	for j in q:
		count = count + 1
		p = int(j) + d
		if(p > 9):
			a = 9 - int(j)
			d = d - a
		else:
			break
	print count


k=int(raw_input())
n=str(raw_input())

inp=list(n)

inp.sort()
s=0
for i in inp:
    s+=int(i)

ans=0
if s>=k:
    print 0

else:
    for i in inp:
        k-=9
        ans+=1
        if k<=0:
            print ans
            break


k=int(raw_input())
n=str(raw_input())

inp=list(n)

inp.sort()
s=0
for i in inp:
    s+=int(i)
k-=s
ans=0
if s>=k:
    print 0

else:
    for i in inp:
        k-=(9-int(i))
        ans+=1
        if k<=0:
            print ans
            break


k=int(raw_input())
n=str(raw_input())

inp=list(n)

inp.sort()
s=0
for i in inp:
    s+=int(i)
k-=s
ans=0
if k<=0:
    print 0

else:
    for i in inp:
        k-=(9-int(i))
        ans+=1
        if k<=0:
            print ans
            break


k = int(raw_input())
n = map(int, raw_input())
n.sort()
k -= sum(n)
ans = 0
i = 0
while i < len(n) and k > 0:
    ans += 1
    k -= 9 - n[i]
    i += 1

assert k <= 0
print ans


k=input()
n=raw_input()
Sn=0
for x in n:
    Sn+=int(x)
if Sn>k:
    print 0
else:
    n=map(int, list(n))
    n.sort()
    k-=Sn
    min=0
    while k>0:
        k-=(9-n[min])
        min+=1
    print min


k=input()
n=raw_input()
Sn=0
for x in n:
    Sn+=int(x)
if Sn>k:
    print 0
else:
    n=map(int, list(n))
    n.sort()
    k-=Sn
    min=0
    while k>0:
        k-=n[min]
        min+=1
    print min


k = int(raw_input())
n = map(lambda x: ord(x) - ord('0'), [c for c in raw_input()])

cur = sum(n)
n.sort()

ans = 0
for x in n :
    if cur < k :
        ans += 1
        cur += 9 - x

print ans


def GiveNumber(k, n):
	nSum = 0
	CountTab = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	for ch in n:
		nSum += int(ch)
	if nSum >= k:
		return 0
	for ch in n:
		for i in range(10):
			if int(ch) == i:
				CountTab[i] += 1
				break
	diff = k-nSum
	helpSum = 0
	counter = 0
	for i in range(10):
		for k in range(CountTab[i]):
			helpSum += 9-i
			counter += 1
			if helpSum >= diff:
				return counter

k = map(int, raw_input().split(' '))[0]
n = raw_input()

print (GiveNumber(k, n))


k = input()
n = input()
str_n = str(n)
sum_str = 0
temp = []
for i in str_n:
    sum_str += int(i)
    temp.append(i)
if sum_str > k:     print 0
else:
    ans, change = 0, k - sum_str
    for i in range(len(temp)-1,-1,-1):
        p = len(temp) - i - 1
        if 9 - int(temp[i]) < change:
            ans += (9 - int(temp[i])) * (10 ** p)
            change -= 9 - int(temp[i])
        else:
            ans += change * (10 ** p)
            break
    print ans


k = input()
num = sorted(map(int,list(raw_input())))
sum_num, ans, i = sum(num), 0, 0
while sum_num < k:
    sum_num += (9-num[i])
    i += 1
print i


k = input()
n = input()
str_n = str(n)
sum_str = 0
max_change = 0
for i in str_n:
    sum_str += int(i)
    max_change += (9-int(i))
if sum_str > k:
    print 0
else:
    if k - sum_str > max_change:
        print k - (sum_str + max_change)
    else:
        print k-sum_str


k = input()
num = sorted(map(int,list(raw_input())))
sum_num, ans, i = sum(num), 0, 0
while sum_num < k:
    sum_num += (9-i)
    i += 1
print i


k = input()
n = input()
str_n = str(n)
sum_str = 0
for i in str_n:
    sum_str += int(i)
if sum_str > k:
    print 0
else:
    print k-sum_str


k = input()
n = input()
str_n = str(n)
sum_str = 0
temp = []
for i in str_n:
    sum_str += int(i)
    temp.append(i)
if sum_str > k:     print 0
else:
    re_temp = []
    for i in range(len(temp)-1,-1,-1):
        re_temp.append(temp[i])
    change = k - sum_str
    # print re_temp
    ans = 0
    for i in range(len(re_temp)):
        if change <= 0:     break
        else:
            p = 9 - int(re_temp[i])
            if change >= p:
                change -= p
                ans += p * (10 ** i)
            else:
                ans += change * (10 ** i)
                break
    print ans


import Queue

pq = Queue.PriorityQueue()
k = int(raw_input())
n = int(raw_input())

soma = 0
auxN = n
while (auxN > 0):
	pq.put(auxN%10)
	soma += auxN % 10
	auxN = auxN / 10

if soma >= k:
	print 0
else:
	ans = 0
	while not pq.empty():
		soma += 9-pq.get()
		ans += 1
		if (soma >= k):
			break

	if (soma >= k):
		print ans
	else:
		print 0


import Queue

pq = Queue.PriorityQueue()
k = int(raw_input())
n = raw_input()

soma = 0
auxN = n

for i in xrange(len(auxN)):
	pq.put(int(auxN[i]))
	soma += int(auxN[i])

if soma >= k:
	print 0
else:
	ans = 0
	while not pq.empty():
		soma += 9-pq.get()
		ans += 1
		if (soma >= k):
			break

	if (soma >= k):
		print ans
	else:
		print 0


k = int(raw_input())
n = int(raw_input())

soma = 0
auxN = n
aux = []
while (auxN > 0):
	aux.append(auxN%10)
	soma += auxN % 10
	auxN = auxN / 10

if soma >= k:
	print 0
else:
	ans = 0
	aux.sort()
	for i in aux:
		soma += 9-i
		ans += 1
		if (soma >= k):
			break

	if (soma >= k):
		print ans
	else:
		print 0


k = input()
n = input()

k = int(k)
n = int(n)
arq = [int(ha) for ha in str(n)];
arq.sort()
leng = len(arq)

sumq = 0
ans = 0
for i in range(leng):
	sumq = sumq + arq[i]
for i in range(leng):
	if (k <= sumq):
		break
	else:
		ans = ans + 1
		sumq = sumq + 9-arq[i]

print ans


k = input()
n = raw_input()
a = [int(i) for i in n]
a.sort()

currentSum = sum(a)
if currentSum >= k:
    print 0
else:
    ans = 0
    i = 0
    while currentSum < k:
        currentSum += (9-a[i])
        ans += 1
        i += 1
    print ans


k = int(raw_input())
n = sorted(map(int, raw_input().strip()))
tot = sum(n)
ans = 0
for i in n:
  if tot >= k:
    break
  tot += 9 - i
  ans += 1
print ans


#include <stdio.h>

int main(int argc, char const *argv[])
{
    int max_sum;
    scanf("%d\n", &max_sum);

    int counts[10] = {0,};
    int c, sum = 0;
    while ((c = getchar()) != '\n') {
        c -= '0';
        counts[c]++;
        sum += c;
    }

    int min_num = 0;
    int mods = 0;
    while (sum < max_sum) {
        while (counts[min_num] < 1) {
            min_num++;
        }

        counts[min_num]--;
        sum += 9 - min_num;
        mods++;
    }

    printf("%d\n", mods);
    return 0;
}


#include <stdio.h>

int main(int argc, char const *argv[])
{
    int max_sum;
    scanf("%d\n", &max_sum);

    int counts[10] = {0,};
    int c, sum = 0;
    while ((c = getchar()) != '\n') {
        c -= '0';
        counts[c]++;
        sum += c;
    }

    int min_num = 1;
    int mods = 0;
    while (sum < max_sum) {
        while (counts[min_num] < 1) {
            min_num++;
        }

        counts[min_num]--;
        sum += 9 - min_num;
        mods++;
    }

    printf("%d\n", mods);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
int compare( const void* a, const void* b)
{
      return ( *(char*)a - *(char*)b );

}
int main()
{
    int n,i=0,s=0,r=0,p=0,ss=0;
    char k[1000003];
    scanf("%d",&n);
    scanf("%s",k);
    while(k[i]!='\0'){
        s+=(int)(k[i]-'0');
        i++;
        ss++;
    }
    if(s>=n)
    {
    printf("%d",0);
    return 0;
    }
    r=n-s;
    qsort( k, ss, sizeof(char), compare );
     i=0;
    while(k[i]!='\0' && r>0){
        p++;
        r-=(9-(int)(k[i]-'0'));
        i++;
    }
    printf("%d",p);
    return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
int k,A[100000],i,sum=0,j,result=0,a=0;
char ch[100000],dh;
scanf("%d",&k);
scanf("%c",&dh);
 scanf("%[^\n]%*c",ch);
for(i=0;i<strlen(ch);i++){
    A[i]=ch[i]-48;
    sum=sum+A[i];
    //sum=sum+A[i];
}
if(sum>=k)
    printf("0");
else{
for(j=9;j>=0;j--){
    for(i=0;i<strlen(ch);i++){
        if(A[i]==j){
            result=result+A[i];
            a=a+1;
            if(result+9*(strlen(ch)-a)>=k)
                continue;
            else{
                a=a-1;
                break;
            }

        }
    }
}
printf("%d",strlen(ch)-a);
}
return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
int k,A[100000],i,sum=0,j,result=0,a=0;
char ch[100000],dh;
scanf("%d",&k);
scanf("%c",&dh);
 scanf("%[^\n]%*c",ch);
for(i=0;i<strlen(ch);i++){
    A[i]=ch[i]-48;
    sum=sum+A[i];
    //sum=sum+A[i];
}
if(sum>=k)
    printf("0");
else{
for(j=8;j>=0;j--){
    for(i=0;i<strlen(ch);i++){
        if(A[i]==j){
            result=result+A[i];
            a=a+1;
            if(result+9*(strlen(ch)-a)>=k)
                continue;
            else{
                a=a-1;
                break;
            }

        }
    }
}
printf("%d",strlen(ch)-a);
}
return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
int k,A[100000],i,sum=0,j,result=0;
char ch[100000],dh;
scanf("%d",&k);
scanf("%c",&dh);
 scanf("%[^\n]%*c",ch);
for(i=0;i<strlen(ch);i++){
    A[i]=ch[i]-48;
    //sum=sum+A[i];
}
for(j=0;j<=9;j++){
    for(i=0;i<strlen(ch);i++){
        if(sum+A[i]<k){
            if(A[i]==j){
                sum=sum+A[i];
                result=result+1;
            }
        }
        else if(sum>k)
            break;
    }

}
if(result==0)
    printf("0");
else if(result==strlen(ch))
    printf("1");
else
    printf("%d",strlen(ch)-result);

}
//for(j=0;j<i;j++){
  //  printf("%d\n",A[i]);
//}
//}


#include<stdio.h>
#include<string.h>
int main(){
int k,A[100000],i,sum=0,j,result=0,a=0,m;
char ch[100000],dh;
scanf("%d",&k);
scanf("%c",&dh);
// scanf("%[^\n]%*c",ch);
for(i=0;i<=100000;i++){
    scanf("%c",&ch[i]);
if(ch[i]=='\n'){
    m=i;
    break;
}
    A[i]=ch[i]-48;
    sum=sum+A[i];
    //sum=sum+A[i];
}
if(sum>=k)
    printf("0");
else{
for(j=9;j>=0;j--){
    for(i=0;i<m;i++){
        if(A[i]==j){
            result=result+A[i];
            a=a+1;
            if(result+9*(m-a)>=k)
                continue;
            else if(result+9*(m-a)<k){
                a=a-1;
                break;
            }
        }
    }
}
printf("%d",m-a);
}
return 0;
}


#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
long long cmpfunc (const void * a, const void * b) {
   return ( *(long long*)a - *(long long*)b );
}

int main(){

long long int test,i,j,n,count,flag=0,o1=0,o2=0,b1,x,m,l,max,k,sum2,min,f,r,o,sum1,sum=0,y,b,count1, a[10]={0};
char a1[1000000];
scanf("%lld%s",&m,a1);
sum1=sum=0;
n=strlen(a1);
for(i=0;i<n;i++){
  x=a1[i]-'0';
  a[9-x]++;
  sum+=x;
}
if(sum>=m){
    printf("0\n");
}else{
    count=0;
    for(i=9;i>=1;i--){
        r=a[i]*i;
        if(r+sum>=m){
            l=m-sum;
            o=l%i+(l%i)?1:0;
            count+=o;
            break;
        }else{
            count+=a[i];
            sum+=r;
        }
    }
    printf("%lld",count);
}
return 0;
}


#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
long long cmpfunc (const void * a, const void * b) {
   return ( *(long long*)a - *(long long*)b );
}

int main(){

long long int test,i,j,n,count,flag=0,o1=0,o2=0,b1,x,m,l,max,k,sum2,min,f,r,o,sum1,sum=0,y,b,count1, a[10]={0};
char a1[1000000];
scanf("%lld%s",&m,a1);
sum1=sum=0;
n=strlen(a1);
for(i=0;i<n;i++){
  x=a1[i]-'0';
  a[9-x]++;
  sum+=x;
}
if(sum>=m){
    printf("0\n");
}else{
    count=0;
    for(i=9;i>=1;i--){
        r=a[i]*i;
        if(r+sum>=m){
            l=m-sum;
            if(l%i==0){
                count+=l/i;
            }else{
            count+=l/i+1;
            }
            break;
        }else{
            count+=a[i];
            sum+=r;
        }
    }
    printf("%lld",count);
}
return 0;
}


#include <stdio.h>
#include <string.h>

#define N 100001

int main() {
	static char s[N + 1];
	static int kk[N];
	int n, k, i, c, sum, cnt;

	scanf("%d%s", &k, s);
	n = strlen(s);
	sum = 0;
	for (i = 0; i < n; i++) {
		sum += (s[i] - '0');
		kk[s[i] - '0']++;
	}
	cnt = 0;
	for (c = '0'; c <= '9'; c++) {
		for (i = 0; i < n; i++)
			if (sum < k && s[i] == c && kk[c - '0']-- > 0) {
				sum += (9 - (c - '0'));
				cnt++;
			}
	}
	printf("%d\n", cnt);
	return 0;
}


#include <math.h>
#include <stdio.h>
#include <string.h>

#define N 100001

int main() {
	static char s[N + 1];
	static int kk[N];
	int n, k, i, c, sum, cnt;

	scanf("%d%s", &k, s);
	n = strlen(s);
	sum = 0;
	for (i = 0; i < n; i++) {
		sum += (s[i] - '0');
		kk[s[i] - '0']++;
	}
	cnt = 0;
	for (c = '0'; c <= '9'; c++) {
		for (i = 0; i < n; i++)
			if (sum < k && s[i] == c && kk[c - '0']-- > 0) {
				sum += (9 - (c - '0'));
				cnt++;
			}
	}
	printf("%d\n", cnt);
	return 0;
}


/* https://codeforces.com/contest/835/submission/29056277 (rainboy) */
#include <stdio.h>
#include <string.h>

#define N 100001

int main() {
	static char s[N + 1];
	static int kk[N];
	int n, k, i, d, sum, cnt;

	scanf("%d%s", &k, s);
	n = strlen(s);
	sum = 0;
	for (i = 0; i < n; i++) {
		sum += (s[i] - '0');
		kk['9' - s[i]]++;
	}
	cnt = 0;
	for (d = 9; d >= 0; d--)
		while (sum < k && kk[d]-- > 0)
			sum += d, cnt++;
	printf("%d\n", cnt);
	return 0;
}


#include <stdio.h>
#include <string.h>

#define N 100001

int main() {
	static char s[N + 1];
	int n, k, i, cnt;

	scanf("%d%s", &k, s);
	n = strlen(s);
	cnt = 0;
	for (i = 0; i < n; i++)
		cnt += (s[i] - '0');
	printf("%d\n", k - cnt < 0 ? 0 : k - cnt);
	return 0;
}


#include <math.h>
#include <stdio.h>
#include <string.h>

#define N 100001

int main() {
	static char s[N + 1];
	int n, k, i, x, cnt;

	scanf("%d%s", &k, s);
	n = strlen(s);
	cnt = 0;
	for (i = 0; i < n; i++)
		cnt += (s[i] - '0');
	x = ceil((double) ((k - cnt) + 8) / (double) 9);
	printf("%d\n", x < 0 ? 0 : x);
	return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int cf(void const *a, void const *b)
{
	return (*(char*)a) - (*(char*)b);
}
int main()
{
	int k, x=0, h, f=0, i;
	char s[200000];

	scanf("%d %s", &k, s);

	for(i=0; i<strlen(s); i++)
	{
		x+=s[i]-'0';
	}
	if(x>=k)
	{
		printf("0");
	}
	else
	{
		qsort(s, strlen(s), sizeof(char), cf);

		for(h=0; h<strlen(s); h++)
		{
			x=x-(s[h]-'0')+9;
			f++;

			if(x>=k)
			{
				break;
			}
		}
		printf("%d", f);
	}
	return 0;
}


#include<stdio.h>
#include<stdlib.h>
int main()
{
	int k,i,a[10]={},count=0,res=0;
	scanf("%d",&k);
	char c;
	getchar();
	while((c=getchar()-'0')>=0)
    {
		res+=c;
		a[c]++;
	}
	if(res<=k)
	{
		for (i=0;i<10;i++)
        {
			while(a[i])
            {
				if(res>=k)
                break;
                a[i]--;
				count++;
				res+=9-i;
			}
		}
	}
	printf("%d",count);
	return  0;
}


#include <stdio.h>
#include <string.h>

int digits[11];

int main()
{
	memset(digits,0,sizeof(digits));
	int i,n,ans,j,k,d;
	int s=0;
	char input[100100];
	scanf("%d\n",&n);
	fgets(input, 100050, stdin);
	for(i=0;i<strlen(input);i++)
	{
		if(input[i]<'0' || input[i]>'9')break;
		s+=(input[i]-'0');
		digits[input[i]-'0']++;
		if(s>n)break;
	}
	ans=0;
	if(s>n)printf("0\n");
	else
	{
		j=0;
		while(1)
		{
			k=9-j;
			if(s+k*digits[j]>n)
			{
				d=n-s;
				d++;
				ans+=(d/k);
				ans++;
				break;
			}
			else
			{
				ans+=digits[j];
				s+=k*digits[j];
				j++;
			}
		}
		printf("%d\n",ans );
	}
	return 0;
}


#include <stdio.h>
#include <string.h>

int main()
{
	int i,n;
	int s=0;
	char input[100100];
	scanf("%d\n",&n);
	fgets(input, 100050, stdin);
	for(i=0;i<strlen(input);i++)
	{
		if(input[i]<'0' || input[i]>'9')break;
		s+=(input[i]-'0');
		if(s>n)break;
	}
	n=n-s;
	if(n<=0)printf("0\n");
	else printf("%d\n",(n/9)+1);
	return 0;
}


#include <stdio.h>
#include <string.h>

int digits[11];

int main()
{
	memset(digits,0,sizeof(digits));
	int i,n,ans,j,k,d;
	int s=0;
	char input[100100];
	scanf("%d\n",&n);
	fgets(input, 100050, stdin);
	for(i=0;i<strlen(input);i++)
	{
		if(input[i]<'0' || input[i]>'9')break;
		s+=(input[i]-'0');
		digits[input[i]-'0']++;
		if(s>n)break;
	}
	ans=0;
	if(s>n)printf("0\n");
	else
	{
		j=0;
		while(1)
		{
			k=9-j;
			if(s+k*digits[j]>=n)
			{
				d=n-s;
				ans+=(d/k);
				if(d%k)ans++;
				break;
			}
			else
			{
				ans+=digits[j];
				s+=k*digits[j];
				j++;
			}
		}
		printf("%d\n",ans );
	}
	return 0;
}


/*
input의 범위가 넓은데, 어떻게 할지 모르겠어서,
k, n 을 int 변수가 나타낼 수 있는 수의 범위 안에서 입력해줬을 때,
정상적으로 작동하도록 작성했습니다.
*/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int k, n;  //초기 입력값 k, n
    int i, j;  //for 문 및 count를 위한 i, j
    int answer, devide, dummy, size=0, sum=0;
    int* Array = malloc(sizeof(int)* size);  // 입력 받은 n의 각 자리수들을 나눠서 저장하기 위해서.

    scanf("%d \n %d",&k,&n);
    devide = n;

    while(devide!=0)  // 몇자리 수인지 알아내기
    {
        devide/=10;
        size++;
    }

    devide = n;

    for(i = 0; i < size; i++)  // 각 자리수를 나눠서 Array에 저장.
    {
        *(Array + i) = devide%10;
        sum+=*(Array + i);
        devide/=10;
    }

    for(j = 1; j < size; j++)  // 작은 수부터 차례대로 배열하기
        for(i = 0; i < size - j; i++)
            if( *(Array + i) > *(Array + i + 1) )
            {
                dummy = *(Array + i);
                *(Array + i)= *(Array + i + 1);
                *(Array + i + 1)=dummy;
            }

    i = 0;
    while(1)  // 마지막 실질적인 계산
    {
        if(k<=sum)
        {
            answer = i;
            break;
        }
        k -= (10 - *(Array + i));
        i++;
    }

    printf("%d\n",answer);  // 출력

    //free(Array);

    //system("pause");
    return 0;
}


#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int divisor(int* Ptr, int n);
int main() {
	int k, n = 0;
	int flag = 0;
	int sum = 0;
	int i = 0;
	int j = 0;
	int* arr=NULL;
	int temp = 0;

	arr = (int*)malloc(sizeof(int)*divisor(arr, n));

	scanf("%d %d", &k, &n);
	for (i = 0; i < divisor(arr, n); i++) {
		sum += arr[i];
	}

	for (i = 0; i < divisor(arr,n)-1; i++) {
		for (j = i; j < divisor(arr, n)-1; j++) {
			if (arr[j] >= arr[j + 1]) {
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	if (sum >= k) {
		flag = 0;
	}
	else{
		while (divisor(arr,n)>flag&&k>0) {
			k -= 9 - arr[i];
			flag++;
			i++;
		}
		if (sum < k) {
			printf("No");
			return 0;
		}
	}
	printf("%d\n", flag);

}
int divisor(int* Ptr, int n) {
	int flag = 0;
	int i = 0;
	while (n > 0) {
		Ptr[i] = n % 10;
		n /= 10;
		i++;
		flag++;
	}
	return flag;
}


#include <stdio.h>

int main()
{
	int k;
	int n;

	scanf("%d", &k);
	scanf("%d", &n);

	int sum_N = 0;
	int digit = 0;
	while (n > 0)
	{
		sum_N += n % 10;
		n -= n % 10;

		digit += 1;

		if( n !=0)
			n /= 10;
	}

	if (sum_N >= k)
		printf("0\n");
	else
	{
		int diff = k - sum_N;

		printf("%d\n", (diff / 8)+1);

	}

	return 0;
}


#include<stdio.h>
int main() {
	int i, j, k, diff, ans = 0, sum = 0;
	int arr[10] = { 0 };
	char temp;
	scanf("%d", &k);
	getchar(); // k를 먼저 받는다
	while (temp != '\n') { // 엔터를 입력하기 전까지의 모든 숫자를 n으로 간주
		scanf("%c", &temp);
		arr[(int)temp - 48]++; // n을 구성하는 0~9의 갯수를 구한다
	}
	for (i = 1; i < 10; i++) {
		sum = sum + i*arr[i]; // n의 각자릿수 합을 구한다
	}
	if (sum >= k) { // n이 원래의 수가 될 수 있다
		printf("0\n");
		return 0;
	}
	/* 최소 몇 자리 만에 원래 수가 될 수 있는 수를 만들어 낼 수 있는지 구해야 한다
		즉 k와 n의 각자릿수 합의 차이를 최소한의 숫자만 바꾸어 매꿔주어야 한다는 것이다
		n의 10의 자리가 0일 경우 이를 9로 바꾸면 하나의 숫자만 바꾸어 합의 차이를 9만큼 줄일 수 있다
		따라서 바꾸어야 할 숫자는 n을 구성하고 있는 숫자 중 0, 1, 2, 3, 4, 5, 6, 7, 8 순이다
	*/
	else { // n이 원래 수가 될 수 없는경우
		diff = k - sum; // 원래숫자의 각자릿수 합과 n의 각자릿수 합의 차
		for (i = 0; i < 9; i++) {
			if (arr[i] != 0) { // 0~8 까지의 숫자가 n의 각 자리수 중 있는지 확인
				for (j = 1; j <= arr[i]; j++) {
					diff = diff - (9 - i);
					ans++;
					if (diff <= 0) {
						printf("%d", ans);
						return 0;
					}
				}
			}
		}
	}
	return 0;
}


#include<stdio.h>
#include<stdlib.h> // 퀵소트부분 코드은 구글에서 뽑앗습니다...ㅠㅠ

int compare(const void *a, const void *b)    // 오름차순 비교 함수 구현
{
	int num1 = *(int *)a;    // void 포인터를 int 포인터로 변환한 뒤 역참조하여 값을 가져옴
	int num2 = *(int *)b;    // void 포인터를 int 포인터로 변환한 뒤 역참조하여 값을 가져옴

	if (num1 < num2)    // a가 b보다 작을 때는
		return -1;      // -1 반환

	if (num1 > num2)    // a가 b보다 클 때는
		return 1;       // 1 반환

	return 0;    // a와 b가 같을 때는 0 반환
}

int main() {
	int k, n; // 문제에서와 같은 입력받을 k,n
	int len = 1; // n의 자릿수를 저장할 변수
	int *ptr; // 동적할당으로 입력받은 n의 각자리 숫자를 저장할거임
	int sum = 0; // n의 각 자리숫자를 모두 더한 합을 저장할 변수를 0으로 초기화 해준다
	int tmp; // n을 저장해둘 다른 변수
	int output = 0; // 출력할 정답
	int i;
	int num; // 코드중간에 값저장을 위해서 필요한 변수

	scanf("%d", &k);
	scanf("%d", &n);

	tmp = n; // n의값을 tmp에 복사해둠

	while (1) {
		tmp = tmp / 10;
		len++;
		if (tmp< 10)
			break;
	} // n의 자릿수 구하기

	ptr = (int *)malloc(sizeof(int)); // ptr변수에 동적할당으로 각자리숫자가 들어갈 공간마련

	for (i = 1; i <= len; i++) {

		if ((n / 10) != 0) {
			ptr[i - 1] = n % 10;// 1의자리숫자부터 ptr[0]저장하고 10의자리는 ptr[1]에저장 이런식
			n = n / 10;
			//printf("#%d\n", ptr[i - 1]);
			ptr = realloc(ptr, sizeof(int)*(i + 1)); // 자리숫자가 남았을 경우 realloc으로 칸을 한칸씩 늘려준다.
		}
		else {
			ptr[i - 1] = n % 10;
			//printf("@%d\n", ptr[i - 1]);
		} // 10으로 나눈 몫이 0일때 마지막남은 한자리숫자를 배열에 저장하고 포문을 종료한다.
	}

	for (i = 0; i < len; i++) {
		sum += ptr[i];
	}

	qsort(ptr, len, sizeof(int), compare); // 저장한 배열을 퀵소트를 이용하여 오름차순으로 정렬

	if (k <= sum) { // 각자리숫자 다더한게 k이상일 때, 아무숫자도 변하지 않아도 된다.
		printf("0\n");

		free(ptr);

		return 0;
	}
	else { // k가 sum보다 클때

		while (sum < k) {
			num = 9 - ptr[output];
			sum += num;
			output++;
		}
	}

	printf("%d\n", output);

	free(ptr);

	return 0;
}


#include <stdio.h> //4번
int main(void){

 int N,A,sum=0,cnt=0;

 scanf("%d%d",&N,&A);
    while (A != 0)
    {
       sum+=A%10;
       A/=10;
    }
    if(N>=sum){
     cnt++;
     printf("%d",cnt);
 }
     else
  printf("0");
      return 0;
}


#include <stdio.h>
#include <stdlib.h>

int compare(void *first, void *second)
{
	if (*(int*)first < *(int*)second)
		return 1;
	else if (*(int*)first > *(int*)second)
		return -1;
	else
		return 0;
}

int main() {
	int num, sum = 0, cnt = 0, orign, tmp;
	int len = 0, i = 1, diff, tmp_sum = 0;
	int arr[10000];

	scanf("%d", &orign);
	scanf("%d", &num);

	while (i < num)
	{
		i *= 10;
		len++;
	}
	for (i = 0; i < len; i++) {
		tmp = num % 10;
		sum += tmp;
		num /= 10;
		arr[i] = 9 - tmp;
	}
	diff = orign - sum;

/*	for (i = 0; i < len; i++) {
		printf("%d", arr[i]);
	}*/

	qsort(arr, len, sizeof(int), compare);

	for (i = 0; i < len; i++) {
		if (tmp_sum >= diff) {
			printf("%d", cnt);
			return 0;
		}
		else {
			tmp_sum += arr[i];
			cnt++;
		}
	}

	return 0;
}


#include<stdio.h>
#include<string.h>
#define Max(a,b) a>b ? a : b
int main()
{
    int k, i, j, d, sum=0, cnt[10]={0}, ans=0, t=0;
    char s[100000];
    scanf("%d %s", &k, s);
    for(i=0; s[i]!='\0'; i++)
    {
        d = s[i]-'0';
        sum += d;
        cnt[d]++;
    }
    for(i=0; i<10; i++)
    {
        for(j=0; j<cnt[i]; j++)
        {
            if(sum < k)
            {
                ans++;
                sum += (9-i);
            }
            else
            {
                t = 1;
                break;
            }
        }
        if(t)
            break;
    }
    printf("%d\n", ans);
    return 0;
}


#include<stdio.h>
#include<string.h>
#define Max(a,b) a>b ? a : b
int main()
{
    int k, i, sum=0;
    char s[100000];
    scanf("%d %s", &k, s);
    for(i=0; s[i]!='\0'; i++)
        sum  += (s[i]-'0');
    printf("%d\n", Max(0,k-sum));
    return 0;
}


#include<stdio.h>
#include<string.h>
#define Max(a,b) a>b ? a : b
int main()
{
    int k, i, j, d, sum=0, cnt[10]={0}, ans=0, t=0;
    char s[100000];
    scanf("%d %s", &k, s);
    for(i=0; s[i]!='\0'; i++)
    {
        d = s[i]-'0';
        sum += d;
        cnt[d]++;
    }
    for(i=1; i<10; i++)
    {
        for(j=0; j<cnt[i]; j++)
        {
            if(sum < k)
            {
                ans++;
                sum += (9-i);
            }
            else
            {
                t = 1;
                break;
            }
        }
        if(t)
            break;
    }
    printf("%d\n", ans);
    return 0;
}


#include <stdio.h>
#include <string.h>

int main(){
  char s[100000];
  long long int i,k,n,suma=0,cuenta=0;
  scanf("%lld%*c", &k);
  scanf("%s", s);

  for (i = 0; i < strlen(s); i++)
    suma+=s[i]-48;

  while (k>suma) {
    if(s[i]!=57){
      n=9-s[i]+48;
      suma+=n;
      i--;
      cuenta++;
    }else{
      i--;
    }
  }

  printf("%lld\n", cuenta);
  return 0;
}


#include <stdio.h>
#include <string.h>

void qs(char lista[],int limite_izq,int limite_der){
    int izq,der,temporal,pivote;
    izq=limite_izq;
    der=limite_der;
    pivote = lista[(izq+der)/2];

    do{
        while(lista[izq]<pivote && izq<limite_der)
          izq++;
        while(pivote<lista[der] && der > limite_izq)
          der--;
        if(izq <=der){
            temporal= lista[izq];
            lista[izq]=lista[der];
            lista[der]=temporal;
            izq++;
            der--;
        }
    }while(izq<=der);
    if(limite_izq<der)
      qs(lista,limite_izq,der);
    if(limite_der>izq)
      qs(lista,izq,limite_der);
}

void rvereseArray(char arr[], int start, int end)
{
    int temp;
    while (start < end)
    {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main(){
  char s[100000];
  long long int i,k,n,suma=0,cuenta=0;
  scanf("%lld%*c", &k);
  scanf("%s", s);

  for (i = 0; i < strlen(s); i++)
    suma+=(s[i]-48);

  qs(s,0,(int)strlen(s)-1);
  rvereseArray(s,0,(int)strlen(s)-1);

  i=(int)strlen(s)-1;
  while(k>suma) {
    if(s[i]!=57){
      n=9-s[i]+48;
      suma+=n;
      cuenta++;
      i--;
    }else{
      i--;
    }
  }
  printf("%lld", cuenta);
  return 0;
}


#include<stdio.h>
#include<stdlib.h>

int main()
{
	int k, i;
	scanf("%d", &k);
	int arr[10] = { 0 };
	char c;
	int op = 0;
	int sum = 0;
	getchar();

	while ((c = getchar() - '0') >= 0){
		sum += c;
		arr[c]++;
	}
	if (sum <= k){
		for (i = 0; i < 10; i++) {
			while(arr[i]) {
				if (sum > k) break;
				arr[i]--;
				op++;
				sum += 9 - i;
			}
		}
	}
	printf("%d", op);

}


#include<stdio.h>
#include<stdlib.h>

int main()
{
	int k, i;
	scanf("%d", &k);
	int arr[10] = { 0 };
	char c;
	int op = 0;
	int sum = 0;
	getchar();

	while ((c = getchar() - '0') >= 0){
		sum += c;
		arr[c]++;
	}
	if (sum <= k){
		for (i = 0; i < 10; i++) {
			while(arr[i]) {
				if (sum >= k) break;
				arr[i]--;
				op++;
				sum += 9 - i;
			}
		}
	}
	printf("%d", op);

}


#include<stdio.h>
#include<stdlib.h>

int main()
{
	int k, i;
	scanf("%d", &k);
	int arr[10] = { 0 };
	char c;
	int op = 0;
	int sum = 0;
	getchar();

	while ((c = getchar() - '0') >= 0){
		sum += c;
		arr[c]++;
	}
	if (sum > k)printf("0");
	else {
		for (i = 0; i < 10; i++) {
			while(arr[i]) {
				if (sum > k) break;
				arr[i]--;
				op++;
				sum += 9 - i;
			}
		}
	}
	printf("%d", op);

}


#include <stdio.h>

int stod(char *num)
{
	int i = 0;

	while(*num)	{
		i += *num - '0';
		num++;
	}

	return i;
}

int digdif(char *num, int k)
{
	int i, cnt;
	char c;

	cnt = 0;
	for(c='0'; c<='9'; c++)	{
		for(i=0; num[i]; i++)	{
			if(num[i]==c)	{
				k -= '9' - c;
				cnt++;
				if(k<=0)	return cnt;
			}
		}
	}
}

int main(void)
{
	int k, dd;
	char num[100100];
	scanf("%d %s", &k, num);

	k -= stod(num);
	if(k<=0)	printf("0\n");
	else {
		dd = digdif(num, k);
		printf("%d\n", dd);
	}

	return 0;
}


import sys
input = sys.stdin.buffer.readline

def main():

    t = int(input())
    for _ in range(t):
        n, m = map(int, input().split())
        M = [list(str(input())[2:m+2]) for _ in range(n)]
        M = [['#']*m] + M + [['#']*m]
        M = [['#']+c+['#'] for c in M]
        #print(M)
        B = []
        G = []
        flag1 = True
        for i in range(1, n+1):
            for j in range(1, m+1):
                if M[i][j] == 'B':
                    for di, dj in (-1, 0), (1, 0), (0, -1), (0, 1):
                        ni, nj = i+di, j+dj
                        if 1 <= ni <= n and 1 <= nj <= m:
                            if M[ni][nj] == '.':
                                M[ni][nj] = '#'
                            if M[ni][nj] == 'G':
                                flag1 = False
                                break
                    B.append((i, j))
                if M[i][j] == 'G':
                    G.append((i, j))
        if not flag1:
            print('No')
            continue
        if len(G) > 0 and M[n][m] == '#':
            print('No')
            continue

        s = []
        s.append((n, m))
        visit = [[-1]*(m+2) for _ in range(n+2)]
        visit[n][m] = 0
        while s:
            y, x = s.pop()
            for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1):
                ny, nx = y+dy, x+dx
                if visit[ny][nx] == -1 and M[ny][nx] != '#':
                    visit[ny][nx] = visit[y][x]+1
                    s.append((ny, nx))
        flag = True
        for sy, sx in G:
            if visit[sy][sx] == -1:
                flag = False
                break
        #print(visit)
        if flag:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':
    main()


def main():

    t = int(input())
    for _ in range(t):
        n, m = map(int, input().split())
        M = [list(str(input())) for _ in range(n)]
        M = [['#']*m] + M + [['#']*m]
        M = [['#']+c+['#'] for c in M]
        B = []
        G = []
        for i in range(1, n+1):
            for j in range(1, m+1):
                if M[i][j] == 'B':
                    for di, dj in (-1, 0), (1, 0), (0, -1), (0, 1):
                        ni, nj = i+di, j+dj
                        if 1 <= ni <= n and 1 <= nj <= m:
                            if M[ni][nj] == '.':
                                M[ni][nj] = '#'
                    B.append((i, j))
                if M[i][j] == 'G':
                    G.append((i, j))

        if len(G) > 0 and M[n][m] == '#':
            print('No')
            continue
        flag = True
        for sy, sx in G:
            s = []
            s.append((sy, sx))
            visit = [[-1]*(m+2) for _ in range(n+2)]
            visit[sy][sx] = 0
            while s:
                y, x = s.pop()
                if y == n and x == m:
                    break
                for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1):
                    ny, nx = y+dy, x+dx
                    if visit[ny][nx] == -1 and M[ny][nx] != '#':
                        visit[ny][nx] = visit[y][x]+1
                        s.append((ny, nx))
            if visit[n][m] == -1:
                flag = False
        if flag:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':
    main()


import sys
input = sys.stdin.buffer.readline

def main():

    t = int(input())
    for _ in range(t):
        n, m = map(int, input().split())
        M = [list(str(input())[2:m+2]) for _ in range(n)]
        M = [['#']*m] + M + [['#']*m]
        M = [['#']+c+['#'] for c in M]
        #print(M)
        B = []
        G = []
        for i in range(1, n+1):
            for j in range(1, m+1):
                if M[i][j] == 'B':
                    for di, dj in (-1, 0), (1, 0), (0, -1), (0, 1):
                        ni, nj = i+di, j+dj
                        if 1 <= ni <= n and 1 <= nj <= m:
                            if M[ni][nj] == '.':
                                M[ni][nj] = '#'
                    B.append((i, j))
                if M[i][j] == 'G':
                    G.append((i, j))

        if len(G) > 0 and M[n][m] == '#':
            print('No')
            continue
        flag = True
        for sy, sx in G:
            s = []
            s.append((sy, sx))
            visit = [[-1]*(m+2) for _ in range(n+2)]
            visit[sy][sx] = 0
            while s:
                y, x = s.pop()
                if y == n and x == m:
                    break
                for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1):
                    ny, nx = y+dy, x+dx
                    if visit[ny][nx] == -1 and M[ny][nx] != '#':
                        visit[ny][nx] = visit[y][x]+1
                        s.append((ny, nx))
            if visit[n][m] == -1:
                flag = False
                break
        for sy, sx in B:
            s = []
            s.append((sy, sx))
            visit = [[-1]*(m+2) for _ in range(n+2)]
            visit[sy][sx] = 0
            while s:
                y, x = s.pop()
                if y == n and x == m:
                    break
                for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1):
                    ny, nx = y+dy, x+dx
                    if visit[ny][nx] == -1 and M[ny][nx] != '#':
                        visit[ny][nx] = visit[y][x]+1
                        s.append((ny, nx))
            if visit[n][m] != -1:
                flag = False
                break
        if flag:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':
    main()


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""

def inar():
    return [int(k) for k in input().split()]

def main():
    for _ in range(int(input())):
        n, m = map(int, input().split())
        ar = []
        for i in range(n):
            ar.append(list(input()))
        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='B'):
                    if(i-1>=0 and ar[i-1][j]=='.'):
                        ar[i-1][j]='#'
                    if (i + 1 < n and ar[i + 1][j] == '.'):
                        ar[i + 1][j] = '#'
                    if (j - 1 >= 0 and ar[i][j-1] == '.'):
                        ar[i][j-1] = '#'
                    if (j + 1 <m and ar[i][j+1] == '.'):
                        ar[i][j+1] = '#'
        q=[]
        visited=[]
        for i in range(n):
            visited.append([False]*m)

        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='.'):
                    q.append((i,j))
                    visited[i][j] = True
        while(q):
            pos=q.pop()
            i=pos[0]
            j=pos[1]
            if (i - 1 >= 0 and ar[i - 1][j] != '#' and visited[i-1][j]==False):
                q.append((i-1,j))
                visited[i-1][j]=True
            if (i + 1 < n and ar[i + 1][j] != '#' and visited[i+1][j]==False):
                q.append((i+1,j))
                visited[i + 1][j] = True
            if (j - 1 >= 0 and ar[i][j-1] != '#' and visited[i][j-1]==False):
                q.append((i,j-1))
                visited[i][j - 1] = True
            if (j + 1 < m and ar[i][j+1] != '#' and visited[i][j+1]==False):
                q.append((i,j+1))
                visited[i][j+1] = True

        good=True
        for i in range(n):
            for j in range(m):
                if((ar[i][j]=='G' and visited[i][j]==False) or (ar[i][j]=='B' and visited[i][j]==True)):
                    good=False
                    break
        if(good):
            print('Yes')
        else:
            print('No')

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""

def inar():
    return [int(k) for k in input().split()]

def main():
    for _ in range(int(input())):
        n, m = map(int, input().split())
        ar = []
        for i in range(n):
            ar.append(list(input()))
        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='B'):
                    if(i-1>=0 and ar[i-1][j]=='.'):
                        ar[i-1][j]='#'
                    if (i + 1 < n and ar[i + 1][j] == '.'):
                        ar[i + 1][j] = '#'
                    if (j - 1 >= 0 and ar[i][j-1] == '.'):
                        ar[i][j-1] = '#'
                    if (j + 1 <m and ar[i][j+1] == '.'):
                        ar[i][j+1] = '#'
        q=[]
        visited=[]
        for i in range(n):
            visited.append([False]*m)

        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='.'):
                    q.append((i,j))
                    visited[i][j] = True
        while(q):
            pos=q.pop()
            i=pos[0]
            j=pos[1]
            visited[i][j]=True
            if (i - 1 >= 0 and ar[i - 1][j] != '#' and visited[i-1][j]==False):
                q.append((i-1,j))
            if (i + 1 < n and ar[i + 1][j] != '#' and visited[i+1][j]==False):
                q.append((i+1,j))
            if (j - 1 >= 0 and ar[i][j-1] != '#' and visited[i][j-1]==False):
                q.append((i,j-1))
            if (j + 1 < m and ar[i][j+1] != '#' and visited[i][j+1]==False):
                q.append((i,j+1))

        good=True
        for i in range(n):
            for j in range(m):
                if((ar[i][j]=='G' and visited[i][j]==False) or (ar[i][j]=='B' and visited[i][j]==True)):
                    good=False
                    break
            if(good==False):
                break
        if(good):
            print('Yes')
        else:
            print('No')

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""

def inar():
    return [int(k) for k in input().split()]

def main():
    for _ in range(int(input())):
        n, m = map(int, input().split())
        ar = []
        for i in range(n):
            ar.append(list(input()))

        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='B'):
                    if(i-1>=0 and ar[i-1][j]=='.'):
                        ar[i-1][j]='#'
                    if (i + 1 < n and ar[i + 1][j] == '.'):
                        ar[i + 1][j] = '#'
                    if (j - 1 >= 0 and ar[i][j-1] == '.'):
                        ar[i][j-1] = '#'
                    if (j + 1 <m and ar[i][j+1] == '.'):
                        ar[i][j+1] = '#'
        q=[]
        visited=[]
        for i in range(n):
            visited.append([False]*m)

        for i in range(n):
            for j in range(m):
                if(ar[i][j]=='.'):
                    q.append((i,j))
                    visited[i][j] = True
        visited[n-1][m-1]=False
        while(q):
            pos=q.pop()
            i=pos[0]
            j=pos[1]
            if (i - 1 >= 0 and ar[i - 1][j] != '#' and visited[i-1][j]==False):
                q.append((i-1,j))
                visited[i-1][j]=True
            if (i + 1 < n and ar[i + 1][j] != '#' and visited[i+1][j]==False):
                q.append((i+1,j))
                visited[i + 1][j] = True
            if (j - 1 >= 0 and ar[i][j-1] != '#' and visited[i][j-1]==False):
                q.append((i,j-1))
                visited[i][j - 1] = True
            if (j + 1 < m and ar[i][j+1] != '#' and visited[i][j+1]==False):
                q.append((i,j+1))
                visited[i][j+1] = True
        if(visited[n-1][m-1]==False):
            print('No')
            continue
        good=True
        for i in range(n):
            for j in range(m):
                if((ar[i][j]=='G' and visited[i][j]==False) or (ar[i][j]=='B' and visited[i][j]==True)):
                    good=False
                    break
        if(good):
            print('Yes')
        else:
            print('No')

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""

def dfs(u, visited, good, d, n, m):
    visited[u] = True
    c = [0, False]
    if (u == n * m):
        c[1] = True

    if (good[u] == 'G'):
        c[0] += 1
    for i in d[u]:
        if (visited[i] == False):
            dr = dfs(i, visited, good, d, n, m)
            c[0] += dr[0]
            c[1] ^= dr[1]
    return c

def inar():
    return [int(k) for k in input().split()]

def main():
    for _ in range(int(input())):
        n, m = map(int, input().split())
        good = [0] * (n * m + 1)
        ar = []
        count = 0
        for i in range(n):
            ar.append(list(input()))
        bl = True
        for i in range(n):
            for j in range(m):
                if (ar[i][j] == 'G'):
                    if (j + 1 < m and ar[i][j + 1] == 'B'):
                        bl = False
                    if (j - 1 >= 0 and ar[i][j - 1] == 'B'):
                        bl = False
                    if (i - 1 >= 0 and ar[i - 1][j] == 'B'):
                        bl = False
                    if (i + 1 < n and ar[i + 1][j] == 'B'):
                        bl = False
                    if (bl == False):
                        break
            if (bl == False):
                break
        if (bl == False):
            print('No')
            continue
        for i in range(n):
            for j in range(m):
                if (ar[i][j] == 'G'):
                    count += 1
                if (ar[i][j] == 'B'):
                    if (j + 1 < m and ar[i][j + 1] == '.'):
                        ar[i][j + 1] = '#'
                    if (j - 1 >= 0 and ar[i][j - 1] == '.'):
                        ar[i][j - 1] = '#'
                    if (i - 1 >= 0 and ar[i - 1][j] == '.'):
                        ar[i - 1][j] = '#'
                    if (i + 1 < n and ar[i + 1][j] == '.'):
                        ar[i + 1][j] = '#'

        if (ar[n - 1][m - 1] == '#' and count > 0):
            print('No')
            continue
        d = defaultdict(list)
        ct = 0
        for i in range(n):
            for j in range(m):
                ct += 1
                if (ar[i][j] == '.' or ar[i][j] == 'G'):
                    if (j + 1 < m and (ar[i][j + 1] == '.' or ar[i][j + 1] == 'G')):
                        d[ct].append(ct + 1)
                    if (j - 1 >= 0 and (ar[i][j - 1] == '.' or ar[i][j - 1] == 'G')):
                        d[ct].append(ct - 1)
                    if (i - 1 >= 0 and (ar[i - 1][j] == '.' or ar[i - 1][j] == 'G')):
                        d[ct].append(ct - m)
                    if (i + 1 < n and (ar[i + 1][j] == '.' or ar[i + 1][j] == 'G')):
                        d[ct].append(ct + m)

                if (ar[i][j] == 'G'):
                    good[ct] = 'G'

        if (len(d) == 0 and count == 0):
            print('Yes')
            continue
        visited = [False] * (n * m + 1)
        ans = False
        for i in range(1, n * m + 1):
            if (i in d):
                val = dfs(i, visited, good, d, n, m)
                # print(val[0],val[1])
                if (val[0] == count and val[1] == True):
                    ans = True
                    break
        if (ans):
            print('Yes')
        else:
            print('No')

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""

def dfs(u, visited, good, d, n, m):
    visited[u] = True
    c = [0, False]
    if (u == n * m):
        c[1] = True

    if (good[u] == 'G'):
        c[0] += 1
    for i in d[u]:
        if (visited[i] == False):
            dr = dfs(i, visited, good, d, n, m)
            c[0] += dr[0]
            c[1] ^= dr[1]
    return c

def inar():
    return [int(k) for k in input().split()]

def main():
    for _ in range(int(input())):
        n, m = map(int, input().split())
        good = [0] * (n * m + 1)
        ar = []
        count = 0
        for i in range(n):
            ar.append(list(input()))
        bl = True
        for i in range(n):
            for j in range(m):
                if (ar[i][j] == 'G'):
                    count += 1
                if (ar[i][j] == 'B'):
                    if (j + 1 < m and ar[i][j + 1] == '.'):
                        ar[i][j + 1] = '#'
                    if (j + 1 < m and ar[i][j + 1] == 'G'):
                        bl = False
                        break

                    if (j - 1 >= 0 and ar[i][j - 1] == '.'):
                        ar[i][j - 1] = '#'
                    if (j - 1 >= 0 and ar[i][j - 1] == 'G'):
                        bl = False
                        break

                    if (i - 1 >= 0 and ar[i - 1][j] == '.'):
                        ar[i - 1][j] = '#'
                    if (i - 1 >= 0 and ar[i - 1][j] == 'G'):
                        bl = False
                        break

                    if (i + 1 < n and ar[i + 1][j] == '.'):
                        ar[i + 1][j] = '#'
                    if (i + 1 < n and ar[i + 1][j] == 'G'):
                        bl = False
                        break
        if (bl == False):
            print('No')
            continue
        if (ar[n - 1][m - 1] == '#' and count > 0):
            print('No')
            continue

        d = defaultdict(list)
        ct = 0
        for i in range(n):
            for j in range(m):
                ct += 1
                if (ar[i][j] == '.' or ar[i][j] == 'G'):
                    if (j + 1 < m and (ar[i][j + 1] == '.' or ar[i][j + 1] == 'G')):
                        d[ct].append(ct + 1)
                    if (j - 1 >= 0 and (ar[i][j - 1] == '.' or ar[i][j - 1] == 'G')):
                        d[ct].append(ct - 1)
                    if (i - 1 >= 0 and (ar[i - 1][j] == '.' or ar[i - 1][j] == 'G')):
                        d[ct].append(ct - m)
                    if (i + 1 < n and (ar[i + 1][j] == '.' or ar[i + 1][j] == 'G')):
                        d[ct].append(ct + m)

                if (ar[i][j] == 'G'):
                    good[ct] = 'G'

        # if (len(d) == 0 and count == 0):
        #     print('Yes')
        #     continue

        visited = [False] * (n * m + 1)
        ans = True
        for i in range(1, n * m + 1):
            if (i in d):
                val = dfs(i, visited, good, d, n, m)
                if (val[0] == count and val[1] == True):
                    ans = True
                    break
                else:
                    ans=False
        if (ans):
            print('Yes')
        else:
            print('No')

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()