MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to One Step of Life with Explanation

PHP Hard PHP Control Flow 17 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around grid, one, step. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Given r c and a grid of 0/1, apply one step of Conway's Game of Life and print new grid.

Input Format

First r c. Next r lines of 0/1.

Output Format

r lines grid.

Constraints

r*c

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $inputText=trim(stream_get_contents(STDIN)); if($inputText==='') exit; $inputLines=preg_split('/\\R/', $inputText); $head=preg_split('/\\s+/', trim($inputLines[0] ?? '')); $r=intval($head[0] ?? 0); $c=intval($head[1] ?? 0); $g=[]; for($i=0;$i<$r;$i++){ $row=str_pad(trim($inputLines[$i+1] ?? ''),$c,'0'); $g[$i]=str_split(substr($row,0,$c)); } $output=[]; for($i=0;$i<$r;$i++){ $s=''; for($j=0;$j<$c;$j++){ $cnt=0; for($di=-1;$di<=1;$di++){ for($dj=-1;$dj<=1;$dj++){ if($di===0 && $dj===0) continue; $ni=$i+$di; $nj=$j+$dj; if($ni<0||$nj<0||$ni>=$r||$nj>=$c) continue; if($g[$ni][$nj]==='1') $cnt++; } } $alive=($g[$i][$j]==='1'); $next='0'; if($alive){ if($cnt===2 || $cnt===3) $next='1'; }else{ if($cnt===3) $next='1'; } $s.=$next; } $output[]=$s; } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
3 3 000 111 000
Output:
010 010 010

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next