10189 - Minesweeper

All about problems in Volume 101. If there is a thread about your problem, please use it. If not, create one with its number in the subject.

Moderator: Board moderators

Zopper
New poster
Posts: 1
Joined: Mon Oct 10, 2011 1:11 am

Re: 10189 - Minesweeper

Post by Zopper »

Alright, I'm getting RE (runtime) errors, anyone see anything wrong here?

Code: Select all

#include <iostream>
#include <string.h>

int main()
{
	int x=-1,y=-1;
	int count=1;

	while(std::cin >> x >> y)
	{
		if(x==0&&y==0)
			return 0;

		char field[10000][10000];
		//*field=new char[x];

		//for(int i=0; i<x; i++)
			//field[i]=new char[y];

		memset(field, '\0', sizeof(field));

		for(int i=1; i<=x; i++)
			for(int j=1; j<=y; j++)
				std::cin >> field[i][j];

		std::cout << "Field #" << count << ":\n";

		for(int i=1; i<=x; i++)
		{
			for(int j=1; j<=y; j++)
			{
				if(field[i][j]=='*')
				{
					std::cout << "*";
				}

				else
				{
					int tmp=0;

					if(field[i-1][j]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i+1][j]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i][j-1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i][j+1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i+1][j+1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i-1][j-1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i+1][j-1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					if(field[i-1][j+1]=='*'&&field[i-1][j]!='\0')
						tmp++;

					std::cout << tmp;
				}
			}

			std::cout << "\n";
		}

		std::cout << "\n";

		count++;

		delete field;
	}
}
datahaven
New poster
Posts: 4
Joined: Thu Nov 10, 2011 3:17 am

Re: 10189 - Minesweeper

Post by datahaven »

This!

Adrian
Zopper wrote:Alright, I'm getting RE (runtime) errors, anyone see anything wrong here?

Code: Select all

		delete field;
datahaven
New poster
Posts: 4
Joined: Thu Nov 10, 2011 3:17 am

Re: 10189-Minesweeper :WA

Post by datahaven »

Your code produces the same output as mine (which works), save for an extra blank line after the very last test case in your code.

Adrian
brwnow
New poster
Posts: 1
Joined: Sat Nov 19, 2011 4:05 am

WA since i was born

Post by brwnow »

Well, i'm not a good english speaker, so i won't say a lot, just the enough

getting WA, and i can't understand the why

input:

Code: Select all

3 3
..*
*..
.*.
8 8
.....*.*
*....*..
........
..***...
..***...
..***.*.
......*.
*....*..
0 0
output:

Code: Select all

Field #1:
12*
*32
2*1

Field #2:
11002*3*
*1002*31
12233210
02***200
03***411
02***4*2
122334*2
*1001*21
pg_faria
New poster
Posts: 1
Joined: Sat Dec 03, 2011 11:22 pm

10189-Minesweeper :WA

Post by pg_faria »

Hello!!

I'm getting a WA too... Here is my C code. I've tried a lot of changes but it didn't work... Could someone help me? Thanks a lot!...

-------------

#include <stdio.h>

#define MAX_L 101
#define MAX_C 101

int main (void)
{
/* Matriz para os dados de entrada */
char M[MAX_L][MAX_C];

/* Matriz com a contagem de minas */
long minas[MAX_L][MAX_C];

/* Linhas e colunas para cada conjunto de dados */
long lin = 1, col = 1;

/* Variáveis utilizadas */
long i, j, fields = 0;

while(scanf("%ld %ld", &lin, &col) != EOF)
{
/* 0 0, Encerra o programa */
if (!lin && !col)
{
return 0;
}

fields++;

/* Leitura dos valores na matriz original */
for(i = 0; i < lin; i++)
{
scanf("%s", M);

for(j = 0; j < col; j++)
{
/* Utiliza um espaço antes do %c */
/* Para ler os dados corretamente */
/* scanf(" %c", &M[j]);*/

/* Inicializa a matriz para a contagem das minas */
minas[j] = 0;
}
}

/* Gera a matriz com a quantidade de minas */
for(i = 0; i < lin; i++)
{
for(j = 0; j < col; j++)
{
if(M[j] == '.')
{
/* Mesma linha e colunas diferentes */
if(M[j+1] == '*' && j < col) minas[j]++;
if(M[j-1] == '*' && j > 0) minas[j]++;

/* Linhas diferentes e mesma coluna */
if(M[i+1][j] == '*' && i < lin) minas[j]++;
if(M[i-1][j] == '*' && i > 0) minas[j]++;

/* Linha posterior e colunas diferentes */
if(M[i+1][j+1] == '*' && i < lin && j < col) minas[i][j]++;
if(M[i+1][j-1] == '*' && i < lin && j > 0) minas[i][j]++;

/* Linha anterior e colunas diferentes */
if(M[i-1][j+1] == '*' && i > 0 && j < col) minas[i][j]++;
if(M[i-1][j-1] == '*' && i > 0 && j > 0) minas[i][j]++;
}
}
}

/* Exibe o resultado */
printf("Field #%ld:\n", fields);

for(i = 0; i < lin; i++)
{
for(j = 0; j < col; j++)
{
/* Exibe '*' onde foi digitado '*' */
if(M[i][j] == '*')
printf("*");
/* Exibe a quantidade de minas para o '.' */
else
printf("%ld", minas[i][j]);
}

printf("\n");
}

/* Espaço entre os testes */
printf("\n");

}

return 0;
}
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: 10189-Minesweeper :WA

Post by brianfry713 »

Don't put a blank line after the last field.
Check input and AC output for thousands of problems on uDebug!
white_snake
New poster
Posts: 3
Joined: Sun Feb 12, 2012 12:57 pm

Minesweeper

Post by white_snake »

Something is weird with the UVA compiler and you definitely need to fix it. I get Compilation Error and on my computer it compiles and runs perfectly on my computer.
Anyway, here is the code.
Thank you very much for your time. :)

Code: Select all

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

int adjecant_mines(int i, int j, int upper, int lower);
char grid[1000][1000];

void print_grid(int n, int m);
void mark_grid(int n, int m);
void reset_grid(void);
int main(void)
{
	int n,m,i,j,field = 1;

	while(scanf("%d %d",&n,&m)!=EOF){

		getchar();
		if((n==0)&&(m==0))
			break;
	reset_grid();	
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
		{
			scanf("%c",&grid[i][j]);
		}
		getchar();
	}
	printf("Field #%d:\n",field);
	
	mark_grid(n,m);
	print_grid(n,m);
	field++;
	}
	return 0;
}
int adjecant_mines(int i, int j, int upper, int lower)
{
	int res  = 0;
	int n,m,t1,t2;
	for(n=-1;n<=1;n++)
	{
	  
		for(m=-1;m<=1;m++)
		{
			t1 = i + n;
			t2 = j + m;
			if(grid[t1][t1]=='*' && t1 > -1 && t2 > -1 && t1 < upper && t2 < lower)
				res ++ ;
		}
	}
	return res;
}

void print_grid(int n, int m)
{
	int i,j;
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
		{
			printf("%c",grid[i][j]);
		}
		printf("\n");
	}
}
void mark_grid(int n, int m) //Mark the grid so that each field gets the value of adjecant mines around it.
{
	int i,j;
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
		{
			if(grid[i][j]=='.')
				grid[i][j] = (char)((int)'0' + adjecant_mines(i,j,n,m));
		}
	}
}
void reset_grid(void)
{
	int i,j;
	for(i=0;i<1000;i++)
	{
		for(j=0;j<1000;j++)
		{
			grid[i][j] = '.';
		}
	}
}
mike65
New poster
Posts: 2
Joined: Mon Feb 13, 2012 9:41 am

Re: Minesweeper

Post by mike65 »

Really?
Try asking to experter on another forum...
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: Minesweeper

Post by brianfry713 »

This compiles in C++.
If you use the // comments you need to use C++, ANSI C only supports /* comments */.
adjecant should be spelled adjacent.
Problem number 10189
Check input and AC output for thousands of problems on uDebug!
brunossbrunoss
New poster
Posts: 1
Joined: Sat Apr 28, 2012 9:54 pm

Yet another minesweeper problem. Please help

Post by brunossbrunoss »

hi, I've spend hours with the problem. This is giving me a wrong ans.
I've read almost every thread regardng the problem but can't fix it.
My code does not produce a blank line at the end.
Am desperate.It would be helpful is someone can spot the error in my code.

Code: Select all

#include<stdio.h>
void print(char field[][150],int r, int c){
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      printf("%c",field[i][j]);
    }
    printf("\n");
  }
}
void calculate(char field[150][150],int r, int c, char result[150][150]){
  for(int i = 0; i < r + 2; i++)
    for(int j = 0; j < c + 2;j++)
      result[i][j] = '0';

  for(int i = 0; i < r; i++){
    for(int j = 0; j < c;j++){
      if(field[i][j] == '*'){
	result[i+1][j+1] = '*';
      }else {
	result[i+1][j+1] = '0';
      }
    }
  }
  for(int i = 0;i < r; i++){
    for(int j = 0; j < c; j++){
      if(field[i][j] =='*')continue;

      if(field[i-1][j-1] == '*') result[i+1][j+1]++;
      if(field[i][j-1] == '*') result[i+1][j+1]++;
      if(field[i+1][j-1] == '*')result[i+1][j+1]++;
      if(field[i-1][j] == '*')result[i+1][j+1]++;
      if(field[i+1][j] == '*')result[i+1][j+1]++;
      if(field[i-1][j+1] == '*')result[i+1][j+1]++;
      if(field[i][j+1] == '*') result[i+1][j+1]++;
      if(field[i+1][j+1] == '*')result[i+1][j+1]++;
    }
  }
  
  //print(result,r+2,c+2);
  for(int i = 1; i <= r;i++){
    for(int j = 1; j <= c;j++){
      printf("%c",result[i][j]);
    }
    printf("\n");
  }
}

int main(){
  int r,c,count = 1,first = 1;
  char field[150][150],s[150],result[150][150];
  while(1){
    scanf("%d %d",&r,&c);
    if(r == 0 && c == 0) break;
    if(first){
      first = 0;
    }else{
      printf("\n");
    }
    //printf("\n");
    for(int i = 0; i < r; i++){
      scanf("%s",s);
      for(int j = 0; s[j] !='\0';j++){
	field[i][j] = s[j];
      }
    }
    //print(field,r,c);
    printf("Field #%d:\n",count);
    calculate(field,r,c,result);
    count++;
  }
  return 0;
}
cjun5
New poster
Posts: 1
Joined: Mon Apr 30, 2012 6:39 pm

10189 - Wrong answer

Post by cjun5 »

I don't know wrong answer.
Help me.

Code: Select all

import java.io.IOException;
import java.util.StringTokenizer;


/*
 * 10189 - Minesweeper
*/
public class Main {
	
	String read;
	String MineString = "*";
	
   public static String readLn (int maxLength) {
            byte lin[] = new byte [maxLength];
            int characterLength = 0, readCharacter = -1;

            try {
                    while (characterLength < maxLength) {
                            readCharacter = System.in.read();
                            if ((readCharacter < 0) || (readCharacter == '\n')) break;
                            lin [characterLength++] += readCharacter;
                    }
            }
            catch (IOException e) {
                    return (null);
            }

            if ((readCharacter < 0) && (characterLength == 0)) return (null); 
            return (new String (lin, 0, characterLength));
    }
	
	public Main()
	{
		Run();
	}
	
	private void Run()
	{
		try
		{
			int matrixCount = 1;
			while((read = readLn(255)) != null)
			{
				read = read.trim();
	            if (read.isEmpty()) {
	                continue;
	            }
				int rowCount = 0;
				int columnCount = 0;
				StringTokenizer tokenizer = new StringTokenizer(read);
				
				rowCount = Integer.parseInt(tokenizer.nextToken());
				columnCount = Integer.parseInt(tokenizer.nextToken());
				
				if(rowCount == 0 && columnCount == 0)
					break;
				
				if(rowCount == 0 || columnCount == 0 || rowCount > 100 || columnCount > 100)
					continue;
				
				/*
				 * mine calculate
				 */
				int[][] matrix = new int[rowCount][columnCount];
				for(int i = 0; i < rowCount; i++){
					read = readLn(255);
					
					for(int j =0; j<columnCount; j++){
						String cell = read.substring(j, j+1);
						if(cell.equals(MineString))
						{
							updateMatrix(matrix, i, j);
						}
					}
				}
				
				/*
				 * Print
				 */
				System.out.println("Field #" + matrixCount + ":");
				PrintMatrix(matrix);
				System.out.println();
				matrixCount++;
			}
		
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	
	
	private void updateMatrix(int[][] matrix, int row, int column)
	{
		matrix[row][column] = -1;
		updateCell(matrix, row-1, column-1);
		updateCell(matrix, row-1, column);
		updateCell(matrix, row-1, column+1);
		updateCell(matrix, row, column-1);
		updateCell(matrix, row, column+1);
		updateCell(matrix, row+1, column-1);
		updateCell(matrix, row+1, column);
		updateCell(matrix, row+1, column+1);
	}
	
	private void updateCell(int[][] matrix, int row, int column)
	{
		if(row < 0 || column < 0 || row > matrix.length-1 || column > matrix[0].length-1)
			return;
		
		if(matrix[row][column] == -1)
			return;
		
		matrix[row][column]++;
	}
	
	private void PrintMatrix(int[][] matrix){
		
		for(int i = 0; i<matrix.length; i++){
			
			for(int j = 0; j<matrix[0].length; j++){
				if(matrix[i][j] == -1)
					System.out.print("*");
				else
					System.out.print(matrix[i][j]);
			}
			System.out.println("");
		}
	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Main();
	}

}
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: 10189 - Wrong answer

Post by brianfry713 »

Don't print a blank line at the end.
Check input and AC output for thousands of problems on uDebug!
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: Yet another minesweeper problem. Please help

Post by brianfry713 »

You are reading outside the array. If j is 0, don't try to check field[j-1]. List the problem number 10189 in your post next time.
Check input and AC output for thousands of problems on uDebug!
Archonist
New poster
Posts: 1
Joined: Mon Apr 30, 2012 11:19 pm

MineSweeper-10189

Post by Archonist »

Problem id: 10189

Code: Select all

i updated the code it doesnt work then too   :evil:  :evil:  :evil:  :evil:  :evil:  :evil:  :evil: 
[code]

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
string line;
using namespace std;
typedef string::size_type (string::*find_t)(const string& delim,
        string::size_type offset) const;
vector<string> Split(const string& s,
                     const string& match,
                     bool removeEmpty=false,
                     bool fullMatch=false)
{
    vector<string> result; // return container for tokens
    string::size_type start = 0, // starting position for searches
                              skip = 1; // positions to skip after a match
    find_t pfind = &string::find_first_of; // search algorithm for matches
    if (fullMatch)
    {
// use the whole match string as a key
// instead of individual characters
// skip might be 0. see search loop comments
        skip = match.length();
        pfind = &string::find;
    }
    while (start != string::npos)
    {
// get a complete range [start..end)
        string::size_type end = (s.*pfind)(match, start);
// null strings always match in string::find, but
// a skip of 0 causes infinite loops. pretend that
// no tokens were found and extract the whole string
        if (skip == 0) end = string::npos;
        string token = s.substr(start, end - start);
        if (!(removeEmpty && token.empty()))
        {
// extract the token and add it to the result list
            result.push_back(token);
        }
// start the next range
        if ((start = end) != string::npos) start += skip;
    }
    return result;
}
int main()
{
string str="";
    int count=0;
    str="";
    while(true)
    {
        getline(cin,str);
        count++;

        vector<string> st= Split(str," ");
        int m=atoi(st[0].c_str());
        int n=atoi(st[1].c_str());
        if(m==0 && n==0)
        {
            break;
        }

         cout<<"Field #"<<count<<":"<<endl;
        char **a;
        int  **output;

        a=new char*[m];
        output=new int*[m];
        for(int i=0; i<m; i++)
        {
            a[i]=new char[n];
            output[i]=new int[n];
        }


        for(int i=0; i<m; i++)
        {
            getline(cin,str);

            for(int j=0; j<n; j++)
            {
                char at=str[j];
                a[i][j]=at;


                output[i][j]=0;
            }
        }


        int tempi=0,tempj=0;

        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {


                if(a[i][j]=='*')
                {

 output[i][j]=-1;

                    tempi=i+1;
                    tempj=j+1;
                    if(j!=0)
                        output[i][j-1]++;
                    if(tempj!=n)
                        output[i][j+1]++;
                    if(tempi!=m)
                    {
                        output[i+1][j]++;
                    }
                    if(i!=0)
                        output[i-1][j]++;

                    if(i!=-0 && j!=0 )
                        output[i-1][j-1]++;


                    if(tempi!=m && j!=0)
                        output[i+1][j-1]++;

                    if(tempi!=m && tempj!=n )
                        output[i+1][j+1]++;

                    if(i!=0 && tempj!=n)
                        output[i-1][j+1]++;




                }


            }


        }

        for(int i=0; i<m; i++)
        {

            for(int j=0; j<n; j++)
            {
                if(a[i][j]=='*')
                {
                    cout<<"*";

                }
                else
                {
                    cout<<output[i][j];
                }
            }
            cout<<endl;


        }
        /*
        i-1 =0
        i+1 = m
        j-1=0
        j+1=n
        */

//boundary condition



    }
return 0;
}
[/code]
it works for sample input but it fails while submitting please tell me where it fails in which test case , i am new please help me out :p thanks in advence :cry:
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: MineSweeper-10189

Post by brianfry713 »

There must be an empty line between field outputs.
Check input and AC output for thousands of problems on uDebug!
Post Reply

Return to “Volume 101 (10100-10199)”